<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 style="float: right" @click="submitbtn">提交</p-button>
      </div>
      <a-card title="供应商资料" style="width: 100%; margin-bottom: 20px">
        <p-grid-form ref="cargoownerdata" :items="custom" />
      </a-card>
      <div style="background: #fff">
        <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="scopecolumns"
                      :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="scopecolumns"
                      :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="scopecolumns"
                      :selectedRowKeys.sync="HealthScopelList"
                      :data-source.sync="HealthScopedata"
                      ref="healthScope"
                      :scroll="{ x: 1000 }"
                    />
                  </div>
                </div>
              </p-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
                  :columns="HealthLicensecolumns"
                  :selectedRowKeys.sync="HealthLicenseList"
                  rowKey="licenseId"
                  :data-source.sync="healthLicenseListdata"
                  ref="license"
                >
                  <div slot="file" slot-scope="text, record">
                    <span class="table-operator" @click="uploadItem(text, record)">详情</span>
                    <!-- <a-divider type="vertical" />
                    <span class="table-operator" @click="deleteItem(text, record)">查看</span>  -->
                    <imgsUpload
                      v-model="isUpload"
                      :isView="lookats"
                      :viewUrllist="uploadIdlist"
                      @completed="item => handleUploadImgs(item, text, record)"
                    ></imgsUpload>
                  </div>
                </p-table-edit-pro>
              </a-card>

              <!-- 供应商与受托人 -->
              <p-card title="供应商与受托人" style="width: 100%">
                <p-table
                  :columns="companyScopecolumns"
                  rowKey="companyTrusteeId"
                  :remoteParams="remoteParams"
                  :remoteUrl="tableRemoteUrl"
                  :remoteBefore="remoteBefore"
                >
                </p-table>
              </p-card>
              <!-- 收货地址 -->
              <!-- <a-card title="收货地址" style="width: 100%">
              <div slot="extra">
                <p-button @click="createrowHealthScope">新增</p-button>
                <p-button>删除</p-button>
              </div>
              <p-table-edit :columns="HealthScopecolumns" :data-source="sitesAllListdata" ref="healthScope" />
            </a-card> -->
            </div>
            <div class="tabs" v-else>
              <p-grid-form ref="ExpandFields" :items="ExpandFields" />
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-spin>
  </div>
</template>

<script>
import pick from 'lodash.pick'
import custom from './config/custom'
import TableEdit from './tableedit'
import API from './api/custom'
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 { getStrategyRegistry } from '@/views/kzyWMS/api/strategy'
import { upcloud_base_chain } from '@/config/serviceSettings'
export default {
  name: 'edit-detail',
  props: {
    data: {
      type: Array,
      default: null,
      active: ''
    },
    detailItem: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      isUpload: false,
      lookats: true,
      remoteParams: {},
      uploadIdlist: [],
      urlList: [
        'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2450565034,2552672880&fm=26&gp=0.jpg',
        'https://ss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/622762d0f703918fd091b3c4523d269759eec478.jpg'
      ],
      ExpandFields,
      HealthLicenseList: [],
      isReady: true,
      required: false,
      //   custom: custom.custom, //货主资料gridform配置
      //   Healthcustom: custom.Healthcustom, //Health 业务范围 三证合一配置
      //   HealthLicensecolumns: custom.HealthLicensecolumns, //证件资料字段
      custom: [],
      Healthcustom: [],
      HealthScopecolumns: [],
      companyScopecolumns: [],
      HealthLicensecolumns: [],
      healthLicenseListdata: [], //证件资料列表
      sitesAllListdata: [], //收货地址列表
      // tabs: ['医药', '制造', '商贸', '扩展', '联系人', '供应商地址'],
      // tabs: ['医药', '联系人', '供应商地址', '拓展字段'],
      tabs: ['医药', '扩展字段'],
      cargoownerinfo: {}, //货主详细信息
      info: {},
      list: [],
      type: '',
      key: 'tab1',
      noTitleKey: 'app',
      uploadline: null,
      HealthScopelList: [],
      scopecolumns: [],
      HealthScopedata: [],
      key: 'key1',
      noTitleKey: 'key1',
      uploadline: null,
      tableRemoteUrl: {
        url: upcloud_base_chain + '/companyTrustee/findTrusteeByCompanyId',
        method: 'get',
        headers: {
          'Content-Type': 'x-www-form-urlencoded'
        },
        params: {}
      },
      tabListNoTitle: [
        {
          key: 'key1',
          tab: '经营范围-商品'
        },
        {
          key: 'key2',
          tab: '经营范围-剂型'
        },
        {
          key: 'key3',
          tab: '经营范围-商品类别'
        }
      ]
    }
  },

  components: {
    TableEdit,
    imgsUpload: ImgsUpload
  },
  created() {
    this.configgird()
    // let warehouse = this.$store.state.user.warehouse
    // let params = { regCode: 'enable_edit_base_data', warehouseId: warehouse.warehouseId }
    // //编辑禁用输入框
    // 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.companyScopecolumns = custom.companyScopecolumns
    //     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 = []
      }

      console.log(this.uploadIdlist)
      this.isUpload = true
      this.uploadline = record
      //   this.lookats = true
    },
    remoteBefore(event, data) {
      data.params.companyId = this.detailItem.supplierId
    },
    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)
      //     }
      //   })
    },
    showUploadImgs(record) {
      //   this.uploadItemIndex = this.queryRefFromName('list').data.findIndex(t => record)
      this.isUpload = true
    },
    //编辑禁用输入框
    configgird() {
      let custom1 = custom.custom
      let Healthcustom = custom.Healthcustom
      let HealthScopecolumns = custom.HealthScopecolumns
      let scopecolumns = custom.scopecolumns
      let HealthLicensecolumns = custom.HealthLicensecolumns
      if (this.detailItem) {
        this.type = '编辑'
        if (!this.$store.getters.hasCurrentOperation('update')) {
          // 不包含update操作权限
          custom1.forEach(item => {
            if (item.name != 'supplierKeywords') {
              item.disabled = true
            }
          })
          Healthcustom.forEach(item => {
            item.disabled = true
          })
          HealthScopecolumns.forEach(item => {
            item.disabled = true
          })
          scopecolumns.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
        })
        scopecolumns.forEach(item => {
          item.disabled = true
        })
        HealthLicensecolumns.forEach(item => {
          item.disabled = false
        })
      }
      this.custom = custom1
      this.Healthcustom = Healthcustom
      this.HealthScopecolumns = HealthScopecolumns
      this.companyScopecolumns = custom.companyScopecolumns
      this.scopecolumns = scopecolumns
      this.HealthLicensecolumns = HealthLicensecolumns
      this.setvalue()
    },
    async setvalue() {
      let that = this
      this.isReady = false
      if (this.detailItem) {
        this.type = '编辑'
        let res = await API.infoById({ id: that.detailItem.supplierId })
        this.cargoownerinfo = res.data
        // this.detailItem.cargoOwnerDesc == null ? (this.detailItem.cargoOwnerDesc = '') : ''
        this.cargoownerinfo.health.businessLicense = this.cargoownerinfo.health.businessLicense + ''
        let ref = this.custom
        let key = []
        ref.forEach(item => {
          key.push(item.name)
        })
        this.$nextTick(() => {
          this.$refs.cargoownerdata.form.resetFields()
          this.$refs.cargoownerdata.form.setFieldsValue(pick(this.cargoownerinfo.master, ...key))
          this.$refs.Healthcustom[0].form.resetFields()
          this.$refs.Healthcustom[0].form.setFieldsValue(
            pick(this.cargoownerinfo.health, ...['businessLicense', 'elecCode'])
          )
          this.healthLicenseListdata = this.cargoownerinfo.healthLicenseList
          this.sitesAllListdata = this.cargoownerinfo.sitesAllList
        })
      } else {
        this.type = '新增'
      }
      this.isReady = true
    },
    deleteItem(text, record) {},
    createrowHealthScope() {
      this.$refs.healthScope[0].createRow()
    },
    delHealthLicense() {
      this.$refs.license[0].removeRow(this.HealthLicenseList)
      // this.HealthLicenseList = []
    },
    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()
          }
        })
      }
    },
    //获取新增请求数据
    getaddinfo() {
      this.$refs.cargoownerdata.form.validateFields((err, value) => {
        if (!err) {
          this.required = true
          this.info.master = value
        } else {
          this.required = false
        }
      })
      this.$refs.Healthcustom[0].form.validateFields((err, value) => {
        if (!err) {
          this.info.health = value
        }
      })
      // Healthcustom
      if (this.$refs.healthScope && this.$refs.license) {
        this.info.healthLicenseList = this.healthLicenseListdata
        this.info.sitesAllList = this.sitesAllListdata
      }
    },
    getupdateinfo() {
      let data = {}
      this.$refs.cargoownerdata.form.validateFields((err, value) => {
        if (!err) {
          data.master = Object.assign(this.cargoownerinfo.master, value)
          this.required = true
        } else {
          this.required = false
        }
      })
      this.$refs.Healthcustom[0].form.validateFields((err, value) => {
        if (!err) {
          console.log(value)
          //   data.health = Object.assign(this.cargoownerinfo.health, value)
          data.health = value
        }
      })
      let supplierId = this.cargoownerinfo.master ? this.cargoownerinfo.master.supplierId : null
      let healthId = this.cargoownerinfo.health ? this.cargoownerinfo.health.healthId : null
      this.healthLicenseListdata.forEach(item => {
        item.supplierId = supplierId
        item.healthId = healthId
      })
      this.sitesAllListdata.forEach(item => {
        item.supplierId = supplierId
        item.healthId = healthId
      })

      data.healthLicenseList = Object.assign(this.cargoownerinfo.healthLicenseList, this.healthLicenseListdata)
      data.sitesAllList = Object.assign(this.cargoownerinfo.sitesAllList, this.sitesAllListdata)

      return data
    },
    async submit() {
      let that = this
      //manufacture制造
      //profiles 扩展
      // ========>
      //master 客户资料
      // sitesAllList 收货地址
      //health 是否三证合一
      //healthLicenseList 证件信息
      if (this.type === '新增') {
        this.getaddinfo()
        let res = await API.addItem(this.info)
        if (res.success) {
          that.$message.success('新增成功')
          setTimeout(() => {
            that.toBack()
          }, 200)
        } else {
          that.$exception(res)
          return
        }
      } else {
        // 编辑
        let data = that.getupdateinfo()
        let res = await API.update(data)
        if (res.success) {
          that.$message.success('修改成功')
          // setTimeout(() => {
          that.toBack()
          // }, 200)
        } else {
          that.$exception(res)
          return
        }
      }
      this.required = false
    },
    setdata(data, refname) {
      this.info[refname] = data
    },
    onTabChange(key, type) {
      this[type] = key
    },
    callback(key) {},

    //经营范围切换
    onTabChange(key, type) {
      console.log(key, type)
      this[type] = key
      var params = {}
      // 单位类型 01：货主 02：供应商 03：客户 04：受托人 05:仓库
      params.companyType = '02'
      //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 {
  & /deep/ .ant-card-body {
    padding: 0px;
  }
  .btngroup {
    width: 100%;
    height: 40px;
  }
  .tabs {
    min-height: 300px;
  }
  .table-operator {
    color: #2b80ff;
    cursor: pointer;
  }
  .table-operator:hover {
    text-decoration: underline;
  }
}
</style>
