<template>
  <zj-page-container>
    <zj-page-fill>
      <div style="box-sizing: border-box; padding:10px;">
        <zj-form-container ref="formRef" :form-data="formData" :form-attributes="{ size: 'mini' }">
          <zj-form-module title="客户信息" label-width="80px" :form-data="formData" :form-items="formItems" />
          <zj-form-module title="商品信息" label-width="80px" :form-data="formData" :form-items="formItems2" />
        </zj-form-container>
      </div>
    </zj-page-fill>
    <div style="box-sizing: border-box; padding: 10px; text-align: right;">
      <el-button type="primary" size="small" @click="queding">确定</el-button>
    </div>
  </zj-page-container>
</template>

<script>
import getLbsAmapRegion from "./getLbsAmapRegion.js"
import ImageUpload from '@/components/file-upload'
import editTable from '@/components/template/editTable.js'
import { getClassifyList } from '@/api/goods'
import { esGoodsList } from '@/api/commodityManagement'
import { esOrderAdd } from '@/api/orderManagement'
import { required, mobileRequired, mobile, httpUrl, email } from '@/components/template/rules_verify.js'
export default {
  components: {ImageUpload},
  mixins: [getLbsAmapRegion, editTable],
  data(){
    return {
      formData: {
        "area": "",
        "brandName": "",
        "city": "",
        "companyName": "",
        "companyWechatId": "",
        "createBy": "",
        "createTime": "",
        "energyLabel": "",
        "esCategoryId": "",
        "esCategoryName": "",
        "esGoodsId": "",
        "esGoodsName": "",
        "esOrderId": "",
        "esOrderInfos": [],
        "fileUrl": [],
        "goodsNote": "",
        "goodsPrice": 0,
        "goodsUrl": "",
        "logisticsCode": "",
        "logisticsName": "",
        "logisticsNo": "",
        "num": 0,
        "overTime": "",
        "payStartTime": "",
        "payTime": "",
        "payType": "",
        "pickType": "",
        "power": "",
        "productionTime": "",
        "province": "",
        "receAddress": "",
        "refundNum": 0,
        "refundPrice": 0,
        "remark": "",
        "saleType": 2,
        "sellId": "",
        "sellMobile": "",
        "sellName": "",
        "sellTime": "",
        "sellUrl": "",
        "sendName": "",
        "sendTime": "",
        "source": "",
        "status": "",
        "street": "",
        "totalAmount": 0,
        "transactionId": "",
        "unit": "",
        "updateBy": "",
        "updateTime": "",
        "userAddressId": "",
        "userMobile": "",
        "userName": "",
        "wechatUserId": "",
        "wechatUserMobile": "",
        "wechatUserName": "",
        "wechatUserUrl": "",
        // 省
        provinceId: "",
        // 市
        cityId: "",
        // 区
        areaId: "",
        // 街道
        streetId: "",
      },
      classifyList: [],
      esGoodsList: []
    }
  },
  computed: {
    formItems(){
      return [{
        name: 'el-input',
        md: 6,
        attributes: { disabled: false },
        formItemAttributes: { label: '客户名称', prop: 'userName', rules:[{ required: true, message: '请填写', trigger: 'blur' }] }
      },{
        name: 'el-input',
        md: 6,
        attributes: { disabled: false },
        formItemAttributes: { label: '客户电话', prop: 'userMobile', rules: mobileRequired }
      },{
        name: 'el-radio',
        options: [
          { label: '到店支付', value: "CASH" },
          { label: '转账支付', value: "TRANSFER" },
          { label: '微信支付', value: "WECHAT" },
        ],
        md: 6,
        attributes: { disabled: this.disabled },
        formItemAttributes: { label: '支付方式', prop: 'payType', rules:[{ required: true, message: '请填写', trigger: 'blur' }] }
      },{
        name: 'el-radio',
        options: [
          { label: '线上销售', value: 1 },
          { label: '线下销售', value: 2 },
        ],
        md: 6,
        attributes: { disabled: true },
        formItemAttributes: { label: '销售方式', prop: 'saleType', rules:[{ required: true, message: '请填写', trigger: 'blur' }] }
      }, ...this.amapRegion, {
        name: 'el-input',
        md: 24,
        attributes: { disabled: false, type:"textarea" },
        formItemAttributes: { label: '备注', prop: 'remark' }
      },{
        md: 24,
        name: 'slot-component',
        formItemAttributes: {
          label: '附件',
          prop: 'fileUrl',
          rules: []
        },
        render: (h, { props, onInput }) => {
          return (
            <ImageUpload fileList={this.formData.fileUrl} limit={1}/>
          )
        }
      }]
    },
    formItems2(){
      return [{
          name: 'slot-component',
          md: 24,
          formItemAttributes: {
            label: '',
            'label-width': '0px',
            prop: 'esOrderInfos',
            rules: [{ required: true, message: '请填写', trigger: 'blur' }]
          },
          render: (h, { props, onInput }) => {
            var { value } = props
            return this.convertTableJson(
              value,
              [
                {
                  columnAttributes: {
                    label: '商品分类',
                    prop: 'esCategoryName'
                  }
                },
                {
                  columnAttributes: {
                    label: '商品名称',
                    prop: 'esGoodsId'
                  },
                  editRender: (h, { row, column, index }) => {
                    return (
                      <div class="redbordererr">
                        <el-form-item
                          label=""
                          label-width="0px"
                          prop={`esOrderInfos.${index}.${column.columnAttributes.prop}`}
                          rules={[{ required: true, message: '请填写', trigger: 'blur' }]}
                        >
                          <el-select 
                              filterable={true}
                              value={row[column.columnAttributes.prop]}
                              onInput={val => {
                                var data = this.esGoodsList.find( item => item.id===val )
                                row[column.columnAttributes.prop] = val
                                row.esCategoryId = data?.categoryId ||''
                                row.esCategoryName = data?.categoryName ||''
                                row.brandName = data?.brand ||''
                                console.log(data)
                                row.unit = '台'
                                row.sjNum = data?.qty ||''
                                row.totalAmount = (Number(data?.price) * Number(data?.qty)).toFixed(2);
                                row.power = data?.power ||''
                                row.productionTime = data?.makeDate ||''
                                row.energyLabel = data?.mark ||''
                              }}
                              placeholder="请输入内容">
                            {this.esGoodsList.filter(item=>!this.formData.esOrderInfos.find(v=>v.esGoodsId==item.id ) || row.esGoodsId==item.id ).map((item, index_) => <el-option key={index_} label={item.goodsName} value={item.id}></el-option>)}
                          </el-select>
                        </el-form-item>
                      </div>
                    )
                  },
                  viewRender: (h, { row, column, index }) => {
                    return (
                      <div class="redbordererr">
                        <el-form-item
                          label=""
                          label-width="0px"
                          prop={`esOrderInfos.${index}.${column.columnAttributes.prop}`}
                          rules={[{ required: true, message: '请填写', trigger: 'blur' }]}
                        >
                          <el-select 
                              disabled={true}
                              value={row[column.columnAttributes.prop]}
                              onInput={val => {
                                row[column.columnAttributes.prop] = val
                              }}
                              placeholder="请输入内容">
                            {this.esGoodsList.map((item, index_) => <el-option key={index_} label={item.goodsName} value={item.id}></el-option>)}
                          </el-select>
                        </el-form-item>
                      </div>
                    )
                  }
                },
                {
                  columnAttributes: {
                    label: '单位',
                    prop: 'unit'
                  }
                },
                {
                  columnAttributes: {
                    label: '上架数量',
                    prop: 'sjNum'
                  }
                },
                {
                  columnAttributes: {
                    label: '订单数量',
                    prop: 'num'
                  },
                  editRender: (h, { row, column, index }) => {
                    return (
                      <div class="redbordererr">
                        <el-form-item
                          label=""
                          label-width="0px"
                          prop={`esOrderInfos.${index}.${column.columnAttributes.prop}`}
                          rules={[{ required: true, message: '请填写', trigger: 'blur' }]}
                        >
                          <el-input
                            value={row[column.columnAttributes.prop]}
                            onInput={val => {
                              row[column.columnAttributes.prop] = val
                              row.totalAmount = (Number(val) * Number(row.goodsPrice)).toFixed(2)
                            }}
                            placeholder="请输入内容"
                          ></el-input>
                        </el-form-item>
                      </div>
                    )
                  },
                  viewRender: (h, { row, column, index }) => {
                    return <div style="padding-left:10px">{row[column.columnAttributes.prop]}</div>
                  }
                },
                {
                  columnAttributes: {
                    label: '商品价格',
                    prop: 'goodsPrice'
                  },
                  editRender: (h, { row, column, index }) => {
                    return (
                      <div class="redbordererr">
                        <el-form-item
                          label=""
                          label-width="0px"
                          prop={`esOrderInfos.${index}.${column.columnAttributes.prop}`}
                          rules={[{ required: true, message: '请填写', trigger: 'blur' }]}
                        >
                          <el-input
                            value={row[column.columnAttributes.prop]}
                            onInput={val => {
                              row[column.columnAttributes.prop] = val
                              row.totalAmount = (Number(val) * Number(row.num)).toFixed(2)
                            }}
                            placeholder="请输入内容"
                          ></el-input>
                        </el-form-item>
                      </div>
                    )
                  },
                  viewRender: (h, { row, column, index }) => {
                    return <div style="padding-left:10px">{row[column.columnAttributes.prop]}</div>
                  }
                },
                {
                  columnAttributes: {
                    label: '金额',
                    prop: 'totalAmount'
                  }
                },
                {
                  columnAttributes: {
                    label: '商品品牌',
                    prop: 'brandName'
                  }
                },
                {
                  columnAttributes: {
                    label: '功率（W）',
                    prop: 'power'
                  }
                },
                {
                  columnAttributes: {
                    label: '制造日期',
                    prop: 'productionTime'
                  }
                },
                {
                  columnAttributes: {
                    label: '能效标识',
                    prop: 'energyLabel'
                  }
                },
              ],
              {
                isEdit: true,
                isAdd: true,
                isDel: true
              },
              {
                add: () => {
                  this.formData.esOrderInfos.push({
                    "area": "",
                    "brandName": "",
                    "city": "",
                    "companyName": "",
                    "companyWechatId": "",
                    "createBy": "",
                    "createTime": "",
                    "energyLabel": "",
                    "esCategoryId": "",
                    "esCategoryName": "",
                    "esGoodsId": "",
                    "esGoodsName": "",
                    "esOrderId": "",
                    "fileUrl": "",
                    "goodsNote": "",
                    "goodsPrice": "",
                    "goodsUrl": "",
                    "logisticsCode": "",
                    "logisticsName": "",
                    "logisticsNo": "",
                    "num": "",
                    "overTime": "",
                    "payStartTime": "",
                    "payTime": "",
                    "payType": "",
                    "pickType": "",
                    "power": "",
                    "productionTime": "",
                    "province": "",
                    "receAddress": "",
                    "refundNum": 0,
                    "refundPrice": 0,
                    "remark": "",
                    "saleType": 2,
                    "sellId": "",
                    "sellMobile": "",
                    "sellName": "",
                    "sellTime": "",
                    "sellUrl": "",
                    "sendName": "",
                    "sendTime": "",
                    "source": "",
                    "status": "",
                    "street": "",
                    "totalAmount": "",
                    "transactionId": "",
                    "unit": "",
                    "updateBy": "",
                    "updateTime": "",
                    "userAddressId": "",
                    "userMobile": "",
                    "userName": "",
                    "wechatUserId": "",
                    "wechatUserMobile": "",
                    "wechatUserName": "",
                    "wechatUserUrl": "",
                    sjNum:""
                  })
                  this.isEditTableIndex = this.formData.esOrderInfos.length - 1
                },
                verify: ({ row, column, index }, isEditTableIndex) => {
                  return new Promise(r => {
                    if (isEditTableIndex > -1) {
                      this.$refs.formRef.validateField(
                        [
                          `esOrderInfos.${isEditTableIndex}.esCategoryId`,
                          `esOrderInfos.${isEditTableIndex}.esGoodsId`,
                          `esOrderInfos.${isEditTableIndex}.num`,
                          `esOrderInfos.${isEditTableIndex}.goodsPrice`,
                        ],
                        v => {
                          if (v) {
                            r(true)
                          } else {
                            r(false)
                          }
                        }
                      )
                    } else {
                      r(true)
                    }
                  })
                },
              }
            )
          }
        }]
    }
  },
  created(){
    getClassifyList({
      status:true,
      type:5
    }).then(res=>{
      this.classifyList = res.data
    })
    esGoodsList({"pageNum":1,"pageSize":-1,"params":[{"param":"a.status","compare":"=","value":"ON"}]}).then(res=>{
      this.esGoodsList = res.data.records
      if(this?.$route?.params?.pageType==="add" && this?.$route?.params?.pageCode){
        var data = this.esGoodsList.find( item => item.id===this?.$route?.params?.pageCode )
        this.formData.esOrderInfos.push({
          "area": "",
          "brandName": data?.brand ||'',
          "city": "",
          "companyName": "",
          "companyWechatId": "",
          "createBy": "",
          "createTime": "",
          "energyLabel": data?.mark ||'',
          "esCategoryId": data?.categoryId ||'',
          "esCategoryName": data?.categoryName ||'',
          "esGoodsId": this?.$route?.params?.pageCode,
          "esGoodsName": "",
          "esOrderId": "",
          "fileUrl": "",
          "goodsNote": "",
          "goodsPrice": "",
          "goodsUrl": "",
          "logisticsCode": "",
          "logisticsName": "",
          "logisticsNo": "",
          "num": "",
          "overTime": "",
          "payStartTime": "",
          "payTime": "",
          "payType": "",
          "pickType": "",
          "power": data?.power ||'',
          "productionTime": data?.makeDate ||'',
          "province": "",
          "receAddress": "",
          "refundNum": 0,
          "refundPrice": 0,
          "remark": "",
          "saleType": 2,
          "sellId": "",
          "sellMobile": "",
          "sellName": "",
          "sellTime": "",
          "sellUrl": "",
          "sendName": "",
          "sendTime": "",
          "source": "",
          "status": "",
          "street": "",
          "totalAmount": (Number(data?.price) * Number(data?.qty)).toFixed(2),
          "transactionId": "",
          "unit": '台',
          "updateBy": "",
          "updateTime": "",
          "userAddressId": "",
          "userMobile": "",
          "userName": "",
          "wechatUserId": "",
          "wechatUserMobile": "",
          "wechatUserName": "",
          "wechatUserUrl": "",
          sjNum:data?.qty ||''
        })
        this.isEditTableIndex = 0
      }
    })
  },
  methods: {
    queding(){
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if(valid){
          esOrderAdd({
            ...this.formData,
            fileUrl: this.formData.fileUrl.map(item=>item.url).join(",")
          }).then(res=>{
            this.$message({ type: 'success', message: `成功!` })
            this.$emit("removeTab")
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
