<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" type="primary" @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 forceRender :default-active-key="2" @change="callback">
          <a-tab-pane forceRender 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="delrowHealthLicense">删除</p-button>
                </div>
                <p-table-edit-pro
                  :columns="HealthLicensecolumns"
                  :selectedRowKeys.sync="HealthLicenselist"
                  :data-source.sync="healthLicenseListdata"
                  ref="license"
                  rowKey="licenseId"
                  :scroll="{ x: 1000 }"
                >
                  <div slot="file" slot-scope="text, record">
                    <span class="table-operator" @click="uploadItem(text, record)">详情</span>
                    <imgsUpload
                      v-model="isUpload"
                      :isView="lookats"
                      :viewUrllist="uploadIdlist"
                      @completed="item => handleUploadImgs(item, text, record)"
                    ></imgsUpload>
                    <!-- slot="[tableColSlots[0]]" slot-scope="text, record" -->
                    <!-- <a-divider type="vertical" />
                    <span class="table-operator" @click="uploadItem(record)">上传</span>
                    <a-divider type="vertical" />
                    <span class="table-operator" @click="deleteItem(record)">查看</span> -->
                    <!-- <a :href="record.picUpload || picsrc" target="_blank">查看</a> -->
                  </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>
            </div>
            <div class="tabs" v-else-if="item === '配送信息'">
              <a-card title="配送信息" style="width: 100%">
                <div slot="extra">
                  <p-button @click="createrowsitesAllList">新增</p-button>
                  <p-button @click="delsitesAllList">删除</p-button>
                </div>
                <p-table-edit-pro
                  rowKey="customerSiteId"
                  :columns="sitesAllList"
                  :selectedRowKeys.sync="sitesList"
                  :data-source.sync="sitesAllListdata"
                  ref="sitesAllList"
                />
              </a-card>
            </div>
            <div class="tabs" v-else-if="item === '联系人'">
              <a-card title="联系人" style="width: 100%">
                <!-- <div slot="extra">
                  <p-button @click="createrowcontactsAllList">新增</p-button>
                  <p-button @click="delcontactsAllList">删除</p-button>
                </div> -->
                <p-table-edit-pro
                  rowKey="customerContactId"
                  :columns="contactsAllList"
                  :selectedRowKeys.sync="contactsList"
                  :data-source.sync="contactsAllListdata"
                  ref="contactsAllList"
                />
              </a-card>
            </div>
            <div class="tabs" v-else-if="item === '拓展字段'">
              <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 moment from 'moment'
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: false,
      uploadIdlist: [],
      picsrc: 'http://www.yiwugo.com/shop/license.html?liceno=92371302MA3TRCK14L&userId=shop_260705',
      contactsAllList: custom.contactsAllList,
      sitesAllList: custom.sitesAllList,
      ExpandFields,
      sitesList: [],
      contactsList: [],
      HealthLicenselist: [],
      isReady: true,
      required: false,
      //   custom: custom.custom, //货主资料gridform配置
      //   Healthcustom: custom.Healthcustom, //Health 业务范围 三证合一配置
      //   HealthScopecolumns: custom.HealthScopecolumns, //经营范围字段
      //   HealthLicensecolumns: custom.HealthLicensecolumns, //证件资料字段
      custom: [],
      Healthcustom: [],
      HealthScopecolumns: [],
      companyScopecolumns: [],
      HealthLicensecolumns: [],
      healthLicenseListdata: [], //证件资料列表
      sitesAllListdata: [], //收货地址列表
      contactsAllListdata: [], //联系人列表
      tabs: ['配送信息', '联系人', '医药', '拓展字段'],
      cargoownerinfo: {}, //货主详细信息
      info: {},
      list: [],
      type: '',
      key: 'tab1',
      noTitleKey: 'app',
      uploadline: null,
      remoteParams: {},
      tableRemoteUrl: {
        url: upcloud_base_chain + '/companyTrustee/findTrusteeByCompanyId',
        method: 'get',
        headers: {
          'Content-Type': 'x-www-form-urlencoded'
        },
        params: {}
      },
      HealthScopelList: [],
      scopecolumns: [],
      HealthScopedata: [],
      key: 'key1',
      noTitleKey: 'key1',
      uploadline: null,
      tabListNoTitle: [
        {
          key: 'key1',
          tab: '经营范围-商品'
        },
        {
          key: 'key2',
          tab: '经营范围-剂型'
        },
        {
          key: 'key3',
          tab: '经营范围-商品类别'
        }
      ]
    }
  },

  components: {
    TableEdit,
    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 = []
      }
      this.isUpload = true
      this.uploadline = record
      //   this.lookats = true
    },
    remoteBefore(event, data) {
      data.params.companyId = this.detailItem.customerId
    },
    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 custom = this.custom
      //   let Healthcustom = this.Healthcustom
      //   let HealthScopecolumns = this.HealthScopecolumns
      //   let HealthLicensecolumns = this.HealthLicensecolumns
      //   let sitesAllList = this.sitesAllList
      //   let contactsAllList = this.contactsAllList

      let custom1 = custom.custom
      let Healthcustom = custom.Healthcustom
      let HealthScopecolumns = custom.HealthScopecolumns
      let scopecolumns = custom.scopecolumns
      let HealthLicensecolumns = custom.HealthLicensecolumns
      let sitesAllList = custom.sitesAllList
      let contactsAllList = custom.contactsAllList

      if (this.detailItem) {
        this.type = '编辑'

        if (!this.$store.getters.hasCurrentOperation('update')) {
          custom1.forEach(item => {
            if (item.name != 'customerKeywords') {
              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
          })
          contactsAllList.forEach(item => {
            item.disabled = true
          })
          // sitesAllList.forEach(item => {
          //   if ('sitesAllList'==item.dataIndex) {
          //     return
          //   }
          //   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
        })
        scopecolumns.forEach(item => {
          item.disabled = true
        })
        contactsAllList.forEach(item => {
          item.disabled = false
        })
        sitesAllList.forEach(item => {
          item.disabled = false
        })
      }
      this.custom = custom1
      this.Healthcustom = Healthcustom
      this.HealthScopecolumns = HealthScopecolumns
      this.companyScopecolumns = custom.companyScopecolumns
      this.HealthLicensecolumns = HealthLicensecolumns
      this.scopecolumns = scopecolumns
      this.sitesAllList = sitesAllList
      this.contactsAllList = contactsAllList
      this.setvalue()
    },
    async setvalue() {
      let that = this
      //   this.isReady = false
      if (this.detailItem) {
        this.type = '编辑'
        let res = await API.infoById({ id: that.detailItem.customerId })
        this.cargoownerinfo = res.data
        this.cargoownerinfo.master.cargoOwnerDesc ? (this.cargoownerinfo.master.cargoOwnerDesc = '') : null
        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({
            businessLicense: that.cargoownerinfo.health ? that.cargoownerinfo.health.businessLicense.toString() : null,
            elecCode: that.cargoownerinfo.health ? that.cargoownerinfo.health.elecCode : null
          })

          this.contactsAllListdata = this.cargoownerinfo.contactsAllList
          this.sitesAllListdata = this.cargoownerinfo.sitesAllList
          this.cargoownerinfo.healthLicenseList.forEach(item => {
            item.startAt = moment(item.startAt).format('YYYY-MM-DD')
            item.endAt = moment(item.endAt).format('YYYY-MM-DD')
            item.gmtCreate = moment(item.gmtCreate).format('YYYY-MM-DD')
            item.gmtModified = moment(item.gmtModified).format('YYYY-MM-DD')
            // console.log(moment(item.startAt).format('YYYY-MM-DD'))
          })
          this.healthLicenseListdata = this.cargoownerinfo.healthLicenseList
        })
      } else {
        this.type = '新增'
        this.custom.forEach(item => {
          item.disabled = false
        })
      }
      this.isReady = true
    },
    deleteItem(text, record) {},
    delrowHealthLicense() {
      //   this.$refs.license[0].removeRow(this.HealthLicenselist)
      if (this.HealthLicenselist.length > 0) {
        this.$refs.license[0].removeRow(this.HealthLicenselist)
        this.HealthLicenselist = []
      } else {
        this.$message.warn('请先勾选数据')
      }
    },
    createrowsitesAllList() {
      this.$refs.sitesAllList[0].createRow()
    },

    delsitesAllList() {
      //   this.$refs.sitesAllList[0].removeRow(this.sitesList)

      if (this.sitesList.length > 0) {
        this.$refs.sitesAllList[0].removeRow(this.sitesList)
        this.sitesList = []
      } else {
        this.$message.warn('请先勾选数据')
      }
    },
    delcontactsAllList() {
      //   this.$refs.contactsAllList[0].removeRow(this.contactsList)

      if (this.contactsList.length > 0) {
        this.$refs.contactsAllList[0].removeRow(this.contactsList)
        this.contactsList = []
      } else {
        this.$message.warn('请先勾选数据')
      }
    },
    createrowHealthLicense() {
      this.$refs.license[0].createRow()
    },
    createrowcontactsAllList() {
      this.$refs.contactsAllList[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() {
      let master
      let health
      let healthLicenseList
      let contactsAllList
      let sitesAllList
      this.$refs.cargoownerdata.form.validateFields((err, value) => {
        if (!err) {
          this.required = true
          this.info.master = value
          master = value
        } else {
          this.required = false
        }
      })
      this.$refs.Healthcustom[0].form.validateFields((err, value) => {
        if (!err) {
          this.info.health = value
          health = value
        }
      })
      healthLicenseList = this.healthLicenseListdata
      sitesAllList = this.sitesAllListdata
      contactsAllList = this.contactsAllListdata
      //配送信

      let data = {
        master,
        health,
        healthLicenseList,
        sitesAllList,
        contactsAllList
      }
      return data
    },
    //修改数据
    getupdateinfo() {
      let data = {}
      data = this.getaddinfo()
      let customerId = this.cargoownerinfo.master.customerId
      let healthId = this.cargoownerinfo.health ? this.cargoownerinfo.health.healthId : null
      data.healthLicenseList.forEach(item => {
        item.customerId = customerId
        item.healthId = healthId
      })
      data.sitesAllList.forEach(item => {
        item.customerId = customerId
        item.healthId = healthId
      })
      data.contactsAllList.forEach(item => {
        item.customerId = customerId
        item.healthId = healthId
      })

      data.master.customerId = customerId
      return data
    },
    async submit() {
      //manufacture制造
      //profiles 拓展
      // ========>
      //master 客户资料
      // sitesAllList 收货地址
      //health 是否三证合一
      //healthLicenseList 证件信息
      let data = this.getaddinfo()
      let that = this
      if (this.type === '新增') {
        let res = await API.addItem(data)
        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>
