<template>
  <div class="EditDetail">
    <a-spin style="width: 100%; min-height: 200px" :spinning="!isReady">
      <div class="btngroup">
        <p-button style="float: left" @click="toBack">返回</p-button>
        <p-button class="savebtn" style="float: right" type="primary" @click="submitbtn">提交</p-button>
      </div>

      <a-card title="货主资料" style="width: 100%">
        <p-grid-form ref="cargoownerdata" :items="custom">
          <template slot="diy" slot-scope="value, form">
            <p-cascader-zone-wms
              :paramValue="fields"
              @change="
                (...args) => {
                  handerChange(...args, form)
                }
              "
              @popupVisibleChange="
                (open, value) => {
                  popupVisibleChange(open, form)
                }
              "
            />
          </template>
        </p-grid-form>
        <div class="tab-main">
          <a-tabs :default-active-key="0" @change="callback">
            <a-tab-pane v-for="(item, index) in tabs" :key="index" :tab="item">
              <!-- 医药 -->
              <div class="tabs" v-if="item === '医药'">
                <!-- baseCargoOwnerHealth -->
                <p-grid-form ref="Healthcustom" :items="Healthcustom" />

                <!-- 经营范围 -->
                <p-card
                  style="width: 100%"
                  :tab-list="tabListNoTitle"
                  :active-tab-key="noTitleKey"
                  @tabChange="key => onTabChange(key, 'noTitleKey')"
                >
                  <div style="margin: 10px">
                    <div v-if="noTitleKey === 'key1'">
                      <p-table-edit-pro
                        rowKey="id"
                        :columns="HealthScopecolumns"
                        :selectedRowKeys.sync="HealthScopelList"
                        :data-source.sync="HealthScopedata"
                        ref="healthScope"
                        :scroll="{ x: 1000 }"
                      />
                    </div>
                    <div v-else-if="noTitleKey === 'key2'">
                      <p-table-edit-pro
                        rowKey="id"
                        :columns="HealthScopecolumns"
                        :selectedRowKeys.sync="HealthScopelList"
                        :data-source.sync="HealthScopedata"
                        ref="healthScope"
                        :scroll="{ x: 1000 }"
                      />
                    </div>
                    <div v-else-if="noTitleKey === 'key3'">
                      <p-table-edit-pro
                        rowKey="id"
                        :columns="HealthScopecolumns"
                        :selectedRowKeys.sync="HealthScopelList"
                        :data-source.sync="HealthScopedata"
                        ref="healthScope"
                        :scroll="{ x: 1000 }"
                      />
                    </div>
                  </div>
                </p-card>

                <!-- <a-card title="经营范围" style="width: 100%; margin-bottom: 10px">
                  <div slot="extra">
                     <p-button @click="createrowHealthScope">新增</p-button>
                 <p-button @click="delHealthScope">删除</p-button>
                </div>
                  <p-table-edit-pro
                    rowKey="scopeId"
                    :columns="HealthScopecolumns"
                    :selectedRowKeys.sync="HealthScopelList"
                    :data-source.sync="HealthScopedata"
                    ref="healthScope"
                    :scroll="{ x: 1000 }"
                  />
                </a-card>  -->

                <!-- 证件资料 -->
                <a-card title="证件资料" style="width: 100%">
                  <div slot="extra">
                    <p-button @click="createrowHealthLicense">新增</p-button>
                    <p-button @click="delHealthLicense">删除</p-button>
                  </div>
                  <p-table-edit-pro
                    rowKey="licenseId"
                    :columns="HealthLicensecolumns"
                    :selectedRowKeys.sync="HealthLicenseList"
                    :data-source.sync="HealthLicensedata"
                    ref="license"
                    :scroll="{ x: 1000 }"
                  >
                    <div slot="file" slot-scope="text, record">
                      <!-- <a-divider type="vertical" /> -->
                      <span class="table-operator" @click="uploadItem(text, record)">详情</span>
                      <imgsUpload
                        v-model="isUpload"
                        :isView="lookats"
                        :viewUrllist="uploadIdlist"
                        @completed="item => handleUploadImgs(item, text, record)"
                      ></imgsUpload>
                      <!-- <a-divider type="vertical" />
                      <span class="table-operator" @click="deleteItem(record)">查看</span> -->
                    </div>
                  </p-table-edit-pro>
                </a-card>
              </div>
              <div class="tabs" v-else>
                <p-grid-form ref="ExpandFields" :items="ExpandFields" />
              </div>
            </a-tab-pane>
          </a-tabs>
        </div>
      </a-card>
    </a-spin>
  </div>
</template>

<script>
import pCascaderZoneWms from '@/blocks/CascaderZone/wms.index.js'
import pick from 'lodash.pick'
import custom from './config/custom'
import TableEdit from './tableedit'
import ExpandFields from './config/ExpandFields'
import ImgsUpload from '@/views/kzyWMS/components/ImgsUpload'
for (let i = 0; i < 15; i++) {
  ExpandFields.push({
    type: 'input',
    name: 'fields' + i,
    span: 6,
    label: '拓展字段' + i,
    value: ''
  })
}
import API from '../cargoowner/api/cargoowner'
import { getStrategyRegistry } from '@/views/kzyWMS/api/strategy'

export default {
  name: 'edit-detail',
  props: {
    data: {
      type: Array,
      default: null,
      active: ''
    },
    detailItem: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      isUpload: false,
      lookats: false,
      uploadIdlist: [],
      fields: [],
      ExpandFields,
      isReady: true,
      required: false,
      HealthScopelList: [],
      HealthLicenseList: [],
      //   custom: custom.custom, //货主资料gridform配置
      //   Healthcustom: custom.Healthcustom, //Health 业务范围 三证合一配置
      //   HealthScopecolumns: custom.HealthScopecolumns, //经营范围字段
      //   HealthLicensecolumns: custom.HealthLicensecolumns, //证件资料字段
      custom: [],
      Healthcustom: [],
      HealthScopecolumns: [],
      HealthLicensecolumns: [],
      HealthScopedata: [], //经营范围数据
      HealthLicensedata: [], //证件资料
      // ['医药', '制造', '商贸', '拓展字段1','拓展字段2','拓展字段3'],
      tabs: ['医药', '拓展字段'],
      cargoownerinfo: {}, //货主详细信息
      info: {},
      list: [],
      type: '',
      key: 'key1',
      noTitleKey: 'key1',
      uploadline: null,
      tabListNoTitle: [
        {
          key: 'key1',
          tab: '经营范围-商品'
        },
        {
          key: 'key2',
          tab: '经营范围-剂型'
        },
        {
          key: 'key3',
          tab: '经营范围-商品类别'
        }
      ]
    }
  },

  components: {
    TableEdit,
    pCascaderZoneWms,
    ImgsUpload
  },
  created() {
    this.configgird()
    // let warehouse = this.$store.state.user.warehouse
    // let params = { regCode: 'enable_edit_base_data', warehouseId: warehouse.warehouseId }
    // // setTimeout(()=>{})
    // getStrategyRegistry(params)
    //   .then(res => {
    //     if (!res.data || res.data.regValue != '1') this.configgird()
    //   })
    //   .then(res => {
    //     this.custom = custom.custom
    //     this.Healthcustom = custom.Healthcustom
    //     this.HealthScopecolumns = custom.HealthScopecolumns
    //     this.HealthLicensecolumns = custom.HealthLicensecolumns
    //     this.setvalue()
    //   })
  },
  mounted() {
    // this.setvalue()
  },

  methods: {
    uploadItem(text, record) {
      console.log(text, record)
      if (text) {
        this.uploadIdlist = text.split(',')
      } else {
        this.uploadIdlist = []
      }
      this.isUpload = true
      this.uploadline = record
      //   this.lookats = true
    },
    handleUploadImgs(item, text, record) {
      console.log(item, text, record)
      let destroyPic = item.map(item1 => item1.path).join(',')
      console.log(destroyPic)
      // record.picUpload = destroyPic
      this.uploadline.picUpload = destroyPic
      console.log(this.$refs)
      //   this.$refs.license[0].setFieldsValue({ picUpload: destroyPic })
      this.$refs.license[0].validateFields((err, value) => {
        if (!err) {
          console.log(value)
        }
      })
    },
    //编辑禁用输入框
    configgird() {
      let custom1 = custom.custom
      let Healthcustom = custom.Healthcustom
      let HealthScopecolumns = custom.HealthScopecolumns
      let HealthLicensecolumns = custom.HealthLicensecolumns
      if (this.detailItem) {
        this.type = '编辑'
        // let currentOperations = this.$store.state.permission.currentOperations;
        // if (Array.isArray(currentOperations) && !currentOperations.find(t => t == 'update')){
        if (!this.$store.getters.hasCurrentOperation('update')) {
          // 不包含update操作权限
          custom1.forEach(item => {
            if (item.name != 'zjm') {
              item.disabled = true
            }
          })
          Healthcustom.forEach(item => {
            item.disabled = true
          })
          HealthScopecolumns.forEach(item => {
            item.disabled = true
          })
          HealthLicensecolumns.forEach(item => {
            //   item.disabled = true
          })
        }
      } else {
        custom1.forEach(item => {
          item.disabled = false
        })
        Healthcustom.forEach(item => {
          item.disabled = false
        })
        HealthScopecolumns.forEach(item => {
          item.disabled = false
        })
        HealthLicensecolumns.forEach(item => {
          //   item.disabled = false
        })
      }
      this.custom = custom1
      this.Healthcustom = Healthcustom
      this.HealthScopecolumns = HealthScopecolumns
      this.HealthLicensecolumns = HealthLicensecolumns
      this.setvalue()
    },
    handerChange(...args) {
      this.fields = args[0][0]
    },
    popupVisibleChange(open, form) {},
    async setvalue() {
      let that = this
      this.isReady = false
      if (this.detailItem) {
        this.type = '编辑'
        // this.custom.forEach((item) => {
        //   item.disabled = true
        // })
        let res = await API.infoById({ cargoOwnerId: that.detailItem.cargoOwnerId })
        this.cargoownerinfo = res.data
        this.cargoownerinfo.baseCargoOwnerMst.cargoOwnerDesc == null
          ? (this.cargoownerinfo.baseCargoOwnerMst.cargoOwnerDesc = '')
          : ''
        let ref = this.custom
        let key = []
        ref.forEach(item => {
          key.push(item.name)
        })
        key.push('cargoOwnerDesc')
        this.$nextTick(() => {
          this.$refs.cargoownerdata.form.resetFields()
          let mst = this.cargoownerinfo.baseCargoOwnerMst
          this.fields = [mst.province ? mst.province : '', mst.city ? mst.city : '', mst.area ? mst.area : '']
          this.$refs.cargoownerdata.form.setFieldsValue(pick(this.cargoownerinfo.baseCargoOwnerMst, ...key))
          //   var unifiedSocialCode = null
          //   if (!that.cargoownerinfo.baseCargoOwnerProfiles) {
          //     unifiedSocialCode = ''
          //   } else {
          //     unifiedSocialCode = that.cargoownerinfo.baseCargoOwnerProfiles.unifiedSocialCode
          //   }baseCargoOwnerProfiles
          //   unifiedSocialCode = that.cargoownerinfo.baseCargoOwnerProfiles.unifiedSocialCode || ''
          //   let eleccode = that.cargoownerinfo.baseCargoOwnerProfiles.elecCode || ''
          this.$refs.cargoownerdata.form.setFieldsValue({
            address1: that.fields,
            unifiedSocialCode: that.cargoownerinfo.baseCargoOwnerProfiles?.unifiedSocialCode || '',
            elecCode: that.cargoownerinfo.baseCargoOwnerProfiles?.elecCode || ''
          })
          this.$refs.Healthcustom[0].form.resetFields()
          this.$refs.Healthcustom[0].form.setFieldsValue(
            pick(this.cargoownerinfo.baseCargoOwnerHealth, ...['businessScope', 'isBusinessLicense'])
          )
          //     this.$refs.Healthcustom[0].form.setFieldsValue({
          //     businessLicense: that.cargoownerinfo.health.businessLicense
          //   })
          this.HealthScopedata = this.cargoownerinfo.baseCargoOwnerScopePage.list
          this.HealthLicensedata = this.cargoownerinfo.baseCargoOwnerLicensePage.list
        })
      } else {
        this.type = '新增'
      }
      this.isReady = true
    },
    //删除经营范围
    delHealthScope() {
      if (this.HealthScopelList.length > 0) {
        this.HealthScopedata = this.HealthScopedata.filter(item => {
          return !this.HealthScopelList.some(key => {
            return key == item.scopeId
          })
        })
        this.HealthScopelList = []
      } else {
        this.$message.warn('请先勾选数据')
      }
    },
    // HealthLicenseList 删除证件资料
    delHealthLicense() {
      if (this.HealthLicenseList.length > 0) {
        this.HealthLicensedata = this.HealthLicensedata.filter(item => {
          return !this.HealthLicenseList.some(key => {
            return key == item.licenseId
          })
        })
        // this.$refs.license[0].removeRow(this.HealthLicenseList)
        this.HealthLicenseList = []
      } else {
        this.$message.warn('请先勾选数据')
      }
    },
    deleteItem(text, record) {},
    createrowHealthScope() {
      this.$refs.healthScope[0].createRow()
    },
    createrowHealthLicense() {
      this.$refs.license[0].createRow()
    },
    tabchange(key, item) {
      item.active = key
      this.active = key
    },

    toBack() {
      this.$emit('changeStep', { step: 1, item: null })
    },

    submitbtn() {
      let content
      if (this.type === '新增') {
        this.getaddinfo()
        content = '是否提交新增?'
      } else {
        this.getupdateinfo()
        content = '是否提交修改?'
      }
      if (this.required) {
        this.$confirm({
          content: this.$lang(content),
          onOk: () => {
            return this.submit()
          }
        })
      } else {
        this.$message.warn('有必填项未填')
      }
    },
    getaddinfo() {
      this.$refs.cargoownerdata.form.validateFields((err, value) => {
        if (!err) {
          this.info.baseCargoOwnerMst = value
          this.required = true
        } else {
          this.required = false
        }
      })
      this.$refs.Healthcustom[0].form.validateFields((err, value) => {
        if (!err) {
          console.log(value)
          this.info.baseCargoOwnerHealth = value
          this.required = true
        } else {
          this.required = false
        }
      })
      // Healthcustom
      if (this.$refs.healthScope && this.$refs.license) {
        // this.$refs.healthScope[0].getdata('healthScope')
        // this.$refs.license[0].getdata('license')
        this.$refs.healthScope[0].validateFields((error, values, selectData) => {
          if (!error) {
            this.required = true
            this.info.healthScope = values
          } else {
            this.required = false
          }
        })
        this.$refs.license[0].validateFields((error, values, selectData) => {
          if (!error) {
            this.info.license = values
            this.required = true
          } else {
            this.required = false
          }
        })
        // this.info.healthScope = this.HealthScopecolumns
        // this.info.license = this.HealthLicensedata
      }
      this.setaddress(this.info)
    },
    //修改更新货主数据
    getupdateinfo() {
      let data = {}
      this.required = true
      this.$refs.cargoownerdata.form.validateFields((err, value) => {
        if (!err) {
          data.baseCargoOwnerMst = Object.assign(this.cargoownerinfo.baseCargoOwnerMst, value)
          this.setaddress(data)
        } else {
          this.required = false
        }
      })
      this.$refs.Healthcustom[0].form.validateFields((err, value) => {
        if (!err) {
          console.log(value)
          //   data.baseCargoOwnerHealth = Object.assign(this.cargoownerinfo.baseCargoOwnerHealth, value)
          data.baseCargoOwnerHealth = value
          console.log(data.baseCargoOwnerHealth)
        } else {
          this.required = false
        }
      })
      let cargoOwnerId = this.cargoownerinfo.baseCargoOwnerMst
        ? this.cargoownerinfo.baseCargoOwnerMst.cargoOwnerId
        : null
      //   let healthId = ''
      let healthId = this.cargoownerinfo.baseCargoOwnerHealth ? this.cargoownerinfo.baseCargoOwnerHealth.healthId : null
      let healthScope
      let license
      this.$refs.healthScope[0].validateFields((error, values, selectData) => {
        if (!error) {
          healthScope = values
        } else {
          this.required = false
        }
      })

      this.$refs.license[0].validateFields((error, values, selectData) => {
        if (!error) {
          license = values
        } else {
          this.required = false
        }
      })
      if (Array.isArray(healthScope)) {
        healthScope.forEach(item => {
          item.cargoOwnerId = cargoOwnerId
          item.healthId = healthId
        })
      }
      if (Array.isArray(license)) {
        license.forEach(item => {
          item.cargoOwnerId = cargoOwnerId
          item.healthId = healthId
        })
      }

      data.healthScope = Object.assign(this.cargoownerinfo.baseCargoOwnerScopePage.list, healthScope)
      data.license = Object.assign(this.cargoownerinfo.baseCargoOwnerLicensePage.list, license)
      if (this.required) {
        console.log(data)
        return data
      } else {
      }
    },
    async submit() {
      let that = this
      if (this.type === '新增') {
        this.getaddinfo()
        let res = await API.addItem(this.info)
        if (res.success) {
          that.toBack()
        } else {
          that.$exception(res)
          return
        }
      } else {
        let data = that.getupdateinfo()
        console.log(data)
        let res = await API.update(data)
        if (res.success) {
          that.toBack()
        } else {
          that.$exception(res)
          return
        }
      }
      this.required = false
    },
    setdata(data, refname) {
      this.info[refname] = data
    },
    onTabChange(key, type) {
      this[type] = key
    },
    callback(key) {},
    //设置地址
    setaddress(data) {
      if (this.fields) {
        data.baseCargoOwnerMst.province = this.fields[0]
        data.baseCargoOwnerMst.city = this.fields[1]
        data.baseCargoOwnerMst.area = this.fields[2]
      }
    },
    //经营范围切换
    onTabChange(key, type) {
      console.log(key, type)
      this[type] = key
      var params = {}
      // 单位类型 01：货主 02：供应商 03：客户 04：受托人 05:仓库
      params.companyType = '01'
      //1、商品 2、剂型 3、类别
      if (key === 'key1') {
        // 范围类型（0：剂型， 1：商品； 2：商品类别；取字典值；）
        params.contypes = 1
      } else if (key === 'key2') {
        params.contypes = 0
      } else {
        params.contypes = 2
      }
      console.log(params, 'pppppppppppp')
      API.findScope(params).then(res => {
        if (!res.success) {
          return
        }
        this.HealthScopedata = res.data
      })
    }
  }
}
</script>

<style lang="less" scoped>
.EditDetail {
  // .savebtn {
  //     position: fixed;
  //     top: 20%;
  //     right: 5%;
  //     z-index: 999;
  // }
  & /deep/ .ant-card-body {
    padding: 0px;
  }
  .btngroup {
    width: 100%;
    height: 40px;
  }
  // .tab-main {
  // }
  .tabs {
    min-height: 300px;
    padding: 5px 10px;
  }
  .table-operator {
    color: #2b80ff;
    cursor: pointer;
  }
  .table-operator:hover {
    text-decoration: underline;
  }
}
</style>
