<template>
  <div>
    <cy-info-title style="margin: 10px 0;">
      <span>
        商品信息
      </span>
      <div v-if="$route.query.type !== 'see'" slot="right" style="display: flex; align-items: center;">
        <!-- <el-button type="text" @click="downLoadTemplate">下载商品信息录入模版</el-button>
        <cy-upload
          :default-desc="'导入商品'"
          :upload-type="'import'"
          :action-import-url="importUrl"
          :upload-params="uploadParams"
          style="text-align: middle; margin: 0 6px;"
          @import-success="getImportFile"
        /> -->
        <el-button type="text" @click="handleAddRow">添加</el-button>
      </div>
    </cy-info-title>
    <div style="width: 100%;">
      <cy-comm-table
        ref="commTable"
        :columns="columns"
        :data="tableData"
        :count="0"
      />
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { downloadGoodsTemplate, getGoodsNameList, getCommoditySpid, getSupplierList } from '@/api/myTrade/salesContract'
import { exportFile } from '@/utils'
// import CustomerSelect from '@/components/CustomSelect'

export default {
  components: {
    // CustomerSelect
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    exportType: {
      type: String,
      default: ''
    },
    enterpriseType: {
      type: String,
      default: ''
    },
    detailsInfo: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      importUrl: process.env.VUE_APP_BASE_API + '/salesContract/import/commodity',
      uploadParams: {},
      tableData: [{
        entityNo: '',
        entityName: '',
        declarationName: '',
        name: '',
        model: '',
        packSpec: '',
        number: '',
        priceUnit: '',
        amount: '',
        hsCode: '',
        addedTaxRate: 0,
        exportTaxRebateRate: 0
      }],
      supplierLsit: [],
      goodsList: [], // 商品名称
      goodsSecList: [],
      columns: [
        {
          label: '序号',
          index: true
        },
        {
          label: '供应商名称',
          showTooltip: true,
          width: 150,
          ruleRequired: true,
          render: (h, row, index) => {
            return <el-select
              v-model={ row.entityName }
              disabled={ this.$route.query.type === 'see' }
              popper-class='custom-popper'
              on-change={ (val) => { this.entityNameChange(val, index) } }
            >
              { this.supplierLsit.map(item => {
                return <el-option
                  key={ item.entityName }
                  value={ item.entityName }
                  label={ item.entityName }
                ></el-option>
              }) }
            </el-select>
          }
        },
        {
          label: '商品名称',
          showTooltip: true,
          width: 240,
          ruleRequired: true,
          render: (h, row, index) => {
            return (
              <CustomerSelect
                v-model={ row.name }
                disabled={ this.$route.query.type === 'see' }
                placeholder='请选择商品名称'
                hasClass={true}
                on-search-click={ (val) => { this.searchClick(val, row) } }
                on-search-change={ (val) => { this.searchChange(val, index) } }
              >
                { this.goodsList.map(item => {
                  return this.goodsList.length && <el-option
                    key={ item.spid }
                    value={ item.spid }
                    label={ item.name }
                  ></el-option>
                })}
                { this.goodsSecList.map(item => {
                  return this.goodsSecList.length && <el-option
                    key={ item.hasCode }
                    value={ item.name }
                    label={ item.labelName }
                  ></el-option>
                })}
              </CustomerSelect>
            )
          }
        },
        {
          label: '报关品名',
          showTooltip: true,
          width: 150,
          ruleRequired: true,
          render: (h, row) => {
            return (
              <el-input
                v-model={ row.declarationName }
                disabled={ this.$route.query.type === 'see' }
                placeholder='请输入报关品名'
              ></el-input>
            )
          }
        },
        {
          label: '型号',
          showTooltip: true,
          width: 150,
          render: (h, row) => {
            return (
              <el-input
                v-model={ row.model }
                disabled={ this.$route.query.type === 'see' }
                placeholder='请输入型号'
              ></el-input>
            )
          }
        },
        {
          label: '申报计量单位',
          showTooltip: true,
          width: 150,
          ruleRequired: true,
          render: (h, row) => {
            return (
              <el-input
                v-model={ row.measurementUnit }
                disabled={ this.$route.query.type === 'see' }
                placeholder='请输入申报计量单位'
              ></el-input>
            )
          }
        },
        {
          label: '包装规格',
          showTooltip: true,
          width: 150,
          ruleRequired: true,
          render: (h, row) => {
            return (
              <el-input
                v-model={ row.packSpec }
                disabled={ this.$route.query.type === 'see' }
                placeholder='请输入包装规格'
              ></el-input>
            )
          }
        },
        {
          label: '数量',
          showTooltip: true,
          width: 150,
          ruleRequired: true,
          render: (h, row) => {
            return (
              <el-input
                v-model={ row.number }
                disabled={ this.$route.query.type === 'see' }
                placeholder='请输入数量'
                onChange={ (val) => { this.numberFeildsChang(val, row) } }
              ></el-input>
            )
          }
        },
        {
          label: '销售单价 (USD)',
          showTooltip: true,
          width: 160,
          ruleRequired: true,
          render: (h, row) => {
            return (
              <cy-amount-input
                v-model={ row.priceUnit }
                disabled={ this.$route.query.type === 'see' }
                onChange={ (val) => { this.priceUnitFeildsChang(val, row) } }
              ></cy-amount-input>
            )
          }
        },
        {
          label: '商品金额 (USD)',
          showTooltip: true,
          width: 160,
          render: (h, row) => {
            return <cy-amount-input v-model={ row.amount } disabled={ true }></cy-amount-input>
          }
        },
        {
          label: '操作',
          show: true,
          render: (h, row, index) => {
            const btnList = [
              { msg: '删除', icon: 'el-icon-delete', power: 'projectNumber:empty', category: 'clear' }
            ]
            const options = index !== 0 && btnList.map(item => {
              return this.$route.query.type !== 'see' && (
                <span class='table-icon-box' style='font-size: 14px;' onClick={() => { this.deleteGoods(index) }}>
                  { item.msg }
                </span>
              )
            })
            return <div>{ options }</div>
          }

        }
      ]
    }
  },
  computed: {
    ...mapState('user', {
      userInfo: state => state.userInfo
    })
  },
  watch: {
    detailsInfo: {
      handler(val) {
        if (val && val.length) {
          this.querySupplierLsit()
          this.tableData = val
        }
      },
      immediate: true
    },
    exportType: {
      handler(val) {
        // 供应商名称展示：如果企业类型是内资生产企业&外商投资生产企业 & 出口类型是自营出口就不展示 ||
        // 出口类型是代理代理出口也不展示供应商
        if ((val && val === 'proxy_export') || (val && val === 'self_export' && ['1', '2'].includes(this.enterpriseType))) {
          this.columns = this.columns.slice().filter(el => el.label !== '供应商名称')
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.querySupplierLsit()
  },
  methods: {
    getParams(type) {
      return new Promise((resolve) => {
        if (type === 'temp') {
          resolve(this.tableData)
        } else {
          if (!this.validateTableData()) {
            return
          }
          // 校验一下报关品名的重复性
          if (!this.validateDeclearName()) {
            this.$message.warning('不同“商品名称 / HS编码”下，“报关品名”不允许重复')
            return
          }

          resolve(this.tableData)
        }
      })
    },
    validateTableData() {
      if (this.tableData.length) {
        let i = 0
        while (i < this.tableData.length) {
          if (!((this.exportType === 'proxy_export') || (this.exportType === 'self_export' && ['1', '2'].includes(this.enterpriseType))) && !this.tableData[i].entityName) {
            this.$message.warning(`请选择商品信息第${i + 1}行供应商名称`)
            return false
          }
          // if (!this.tableData[i].name) {
          //   this.$message.warning(`请选择商品信息第${i + 1}行商品名称`)
          //   return false
          // }
          if (!this.tableData[i].measurementUnit) {
            this.$message.warning(`请选择商品信息第${i + 1}行申报计量单位`)
            return false
          }
          if (!this.tableData[i].declarationName) {
            this.$message.warning(`请输入商品信息第${i + 1}行报关品名`)
            return false
          }
          if (!this.tableData[i].packSpec) {
            this.$message.warning(`请选择商品信息第${i + 1}行包装规格`)
            return false
          }
          if (!this.tableData[i].number) {
            this.$message.warning(`请输入商品信息第${i + 1}行数量`)
            return false
          }
          if (!this.tableData[i].priceUnit) {
            this.$message.warning(`请选择商品信息第${i + 1}行销售单价`)
            return false
          }
          if (!this.tableData[i].hsCode) {
            this.$message.warning(`请选择商品信息第${i + 1}行的具体商品名称`)
            return false
          }
          i++
        }
        return true
      }
    },
    // 报关品名校验规则：同一商品名称的HS编码，报关品名不能重复
    validateDeclearName() {
      console.log(this.tableData)
      if (this.tableData.length) {
        const hscodeMap = new Map()

        for (const item of this.tableData) {
          const { hsCode, declarationName } = item

          if (!hscodeMap.has(hsCode)) {
            hscodeMap.set(hsCode, new Set())
          }

          for (const [key, goodsSet] of hscodeMap) {
            if (key !== hsCode && goodsSet.has(declarationName)) {
              return false
            }
          }

          hscodeMap.get(hsCode).add(declarationName)
        }

        return true
      }
    },
    async downLoadTemplate() {
      const res = await downloadGoodsTemplate()

      if (res) {
        exportFile(res)
      }
    },
    async queryGoodsList(name) {
      const res = await getCommoditySpid({ name })

      if (res.success) {
        this.goodsList = res.data
      }
    },
    loadGoodsData(node, reslove) {
      console.log(node)
    },
    async querySupplierLsit() {
      if (this.userInfo.id !== null) {
        const res = await getSupplierList({ userId: this.userInfo.id })

        if (res.success) {
          this.supplierLsit = res.data
        }
      }
    },
    getImportFile(response) {
      if (response.length) {
        this.tableData = response
        this.tableData.forEach((el) => {
          if (el.priceUnit && el.number) {
            el.amount = el.priceUnit * el.number
          } else {
            el.amount = ''
          }
        })
      }
    },
    handleAddRow() {
      this.tableData.push({
        entityNo: '',
        entityName: '',
        name: '',
        model: '',
        declarationName: '',
        packSpec: '',
        number: '',
        priceUnit: '',
        amount: '',
        hsCode: '',
        addedTaxRate: 0,
        exportTaxRebateRate: 0
      })
    },
    deleteGoods(index) {
      this.tableData.splice(index, 1)
    },
    searchClick(val, row) {
      row.name = val
      this.goodsList = []
      this.goodsSecList = []
      this.queryGoodsList(val)
    },
    entityNameChange(val, index) {
      const obj = this.supplierLsit.find(item => item.entityName === val)
      if (!obj) return
      console.log(obj)
      this.tableData[index].entityNo = obj.entityNo
    },
    searchChange(val, index) {
      if (this.goodsList.find(el => el.spid === val)) {
        this.querySecGoodsInfo(val, index)
      }
      const obj = this.goodsSecList.find(item => item.name === val)
      if (!obj) return
      const { name, model, measurementUnit, entityName, packSpec, number, priceUnit, amount, hsCode, addedTaxRate, exportTaxRebateRate } = obj
      this.tableData[index].name = name
      this.tableData[index].model = model
      this.tableData[index].measurementUnit = measurementUnit
      this.tableData[index].entityName = entityName
      this.tableData[index].packSpec = packSpec
      this.tableData[index].number = number
      this.tableData[index].priceUnit = priceUnit || ''
      this.tableData[index].amount = amount || ''
      this.tableData[index].hsCode = hsCode
      this.tableData[index].addedTaxRate = addedTaxRate
      this.tableData[index].exportTaxRebateRate = exportTaxRebateRate
    },
    async querySecGoodsInfo(val, index) {
      const res = await getGoodsNameList({ name: val })

      if (res.success) {
        this.goodsList = []
        this.goodsSecList = res.data
        // hasCode
        this.goodsSecList.forEach(el => {
          if (el.hsCode) {
            el.labelName = `${el.hsCode}-${el.name}`
          }
        })
        if (res.data.length === 1) {
          const { name, model, measurementUnit, entityName, packSpec, number, priceUnit, amount, hsCode, addedTaxRate, exportTaxRebateRate } = res.data[0]
          this.tableData[index].name = name
          this.tableData[index].model = model
          this.tableData[index].measurementUnit = measurementUnit
          this.tableData[index].entityName = entityName
          this.tableData[index].packSpec = packSpec
          this.tableData[index].number = number
          this.tableData[index].priceUnit = priceUnit || ''
          this.tableData[index].amount = amount || ''
          this.tableData[index].hsCode = hsCode
          this.tableData[index].addedTaxRate = addedTaxRate
          this.tableData[index].exportTaxRebateRate = exportTaxRebateRate
        }
      }
    },
    numberFeildsChang(val, row) {
      if (val) {
        const regex = /^\d+(\.\d{1,6})?$/
        if (!regex.test(row.number)) {
          row.number = 0
        }
        if (row.priceUnit !== '' || row.priceUnit !== null) {
          row.amount = (row.number * row.priceUnit).toFixed(2)
        } else {
          row.amount = 0
        }
      } else {
        row.amount = 0
      }
    },
    priceUnitFeildsChang(val, row) {
      if (val) {
        const regex = /^\d+(\.\d{1,2})?$/
        if (!regex.test(row.priceUnit)) {
          row.priceUnit = 0
        }
        if (row.number !== '' || row.number !== null) {
          row.amount = (row.number * row.priceUnit).toFixed(2)
        } else {
          row.amount = 0
        }
      } else {
        row.amount = 0
      }
    }
  }
}
</script>
