<template>
  <div>
    <DropDownSelectFilter 
      :single="true"
      :data="fcList"
      :total-row-count="fcParams.totalRowCount"
      :page-size="fcParams.pageSize"
      :data-empty-message="fcParams.dataEmptyMessage"
      :default-selected="fcDefault"
      :auto-data="dropSelectAutoData"
      @on-popper-show="fcOnPopperShow"
      @on-popper-hide="fcOnPopperHide"
      @on-fkrp-selected="fcOnFkrpSelected"
      @on-input-value-change="fcOnInputValueChange"
      @on-clear="fcOnclear"
      @on-page-change="fcOnPageChange"
      @on-keydown="fcOnKeyDown">
    </DropDownSelectFilter>
    <Modal
      v-model="matrixModal"
      title="矩阵导入"
      width="900"
      :mask="true"
      :mask-closable="true"
      :closable="true"
      :footer-hide="true"
      @on-cancel="handleModalCancel"
    >
      <matrix 
        v-if="matrixModal" 
        :productId="productId"
        :productCode="inputValue"
        :options="matrixOption" 
        @closeMatrix="handleCloseMatrix"
        @refreshData="handleRefreshMainData"
      />
    </Modal>
  </div>
</template>

<script>
  import matrix from './inputMatrixPop.vue';
  const R3 = window.R3;
  const { network, urlSearchParams, store } = R3;
  export default {
    components: {
      matrix
    },
    props: {
      options: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        inputValue: '',
        productId: '',
        matrixModal: false,
        matrixOption: {},
        fcParams: {
          dataEmptyMessage: '暂无数据',
          totalRowCount: 0,
          pageSize: 10,
          pageIndex: 0
        },
        fcList: {},
        fcDefault: [{
          ID: '',
          Label: ''
        }],
        dropSelectAutoData: [],
        skuFormItem: {}
      }
    },
    created() {
    },
    mounted() {
      // 获取条码外键关联字段信息
      this.$nextTick(() => {
        setTimeout(() => {
          const { formName} = this.options
          const { formItemLists } = document.getElementById(formName)._vue_
          const formItems = formItemLists[0].childs
          for (let key in formItems) { 
            if (formItems[key].colname === 'V_T_IESSKU_ID') {
              this.skuFormItem = {...formItems[key]}
              break
            }
          }
        }, 100)
      })

      window.__drpYunqueFcMatrixEnterFun = () => {
        this.handleInputEnter()
      }
      window.__drpYunqueFcMatrixOpenDialog = (url, id) => {
        this.handleOpenMatrixDialog(url, id)
      }
    },
    beforeDestroy() {
      window.__drpYunqueFcMatrixEnterFun = null
      window.__drpYunqueFcMatrixOpenDialog = null
    },
    methods: {
      // 外键关联方法
      async fcOnPopperShow() {
        const params = {
          searchdata: { 
            range: this.fcParams.pageSize,
            startindex: this.fcParams.pageIndex,
            isdroplistsearch: true,
            refcolid: this.skuFormItem.colid
          }
        }
        this.fcParams.totalRowCount = 0
        this.fcList = {}
        network.post('/p/cs/QueryList', urlSearchParams(params)).then(res => {
          this.fcList = res.data.data
          this.fcParams.totalRowCount = res.data.data.totalRowCount
        })
      },
      fcOnPopperHide() {
        this.fcParams.pageIndex = 0
      },
      fcOnFkrpSelected(val) {
        this.$emit('change', val[0].Label)
      },
      async fcOnInputValueChange(val) {
        this.$emit('change', val)
        if (val) {
          const params = {
            ak: val,
            colid: this.skuFormItem.colid,
            fixedcolumns: {}
          }
          network.post('/p/cs/fuzzyquerybyak', urlSearchParams(params)).then(res => {
            if (res.data.code === 0) {
              this.dropSelectAutoData = res.data.data
            }
          })
        }
      },
      fcOnclear() {
      },
      fcOnPageChange(val) {
        this.fcParams.pageIndex = (val - 1) * this.fcParams.pageSize
        this.fcOnPopperShow()
      },
      fcOnKeyDown(event) {
        if (event.keyCode !== 13) {
          return
        }
        this.handleInputEnter()
      },
      handleInputEnter() {
        const {moduleComponentName,formName,tableName} = this.options
        const {saveInfo, updateData} = this.$store.state[moduleComponentName]
        const {formData,formItemLists} = document.getElementById(formName)._vue_
        const mainTableName = this.$route.params.tableName
        const itemId = this.$route.params.itemId
        
        let isSendRequest = true
        let notNullMessage = ''
        let formKey = []
        let formItemData = {...formData, ID: -1}
        const formItem = formItemLists[0].childs
        for (let key in formItem) {
          const item = formItem[key]
          if (item.display !== 'none' && item.isnotnull) {
            formKey.push(item.colname)
          }
          if (item.display !== 'none' && item.isnotnull && !formItemData[item.colname]) {
            isSendRequest = false
            notNullMessage = `${item.coldesc}不能为空！`
            break
          }
        }

        if (!isSendRequest) { return this.$Message.warning(notNullMessage) }

        // 走接口判断PRODUCTCODE是否为条码/商品编码
        const skuCode = formItemData.PRODUCTSKUCODE
        const checkParams = {
          PRODUCTSKUCODE: skuCode
        }
        this.apiCodeCheck(checkParams).then(v => {
          // 判断当前是否为新增
          if (itemId === 'New') {
            if (v.skuId) {
              formItemData['V_T_IESSKU_ID'] = v.skuId
              const params = {
                [mainTableName]: {...updateData[mainTableName].add[mainTableName], ID: -1},
                [tableName]: [formItemData]
              }
              this.apiInputScan(saveInfo.paths, params, 'add')
            } else {
              const params = {
                [mainTableName]: {...updateData[mainTableName].add[mainTableName], ID: -1}
              }
              this.apiInputScan(saveInfo.paths, params, 'add')
            }
          } else {
            // productId存在走框架接口，不存在打开弹框
            if (v.productId) {
              this.handleOpenMatrixDialog(saveInfo.paths, v.productId)
            } else if (v.skuId) {
              formItemData['V_T_IESSKU_ID'] = v.skuId
              const params = {
                [mainTableName]: {ID: itemId},
                [tableName]: [formItemData]
              }
              this.apiInputScan(saveInfo.paths, params, 'modify')
            } else {
              this.$Modal.fcError({
                title: '错误',
                mask:true,
                content: '扫描条码或商品不存在'
              })
            }
          }
        })
      },
      handleOpenMatrixDialog(url, productId) {
        let formKey = []
        const formItem = document.getElementById(this.options.formName)._vue_.formItemLists[0].childs
        for (let key in formItem) {
          const item = formItem[key]
          if (item.display !== 'none' && item.isnotnull) {
            formKey.push(item.colname)
          }
        }
        formKey[0] = 'V_T_IESSKU_ID'
        this.productId = productId
        this.matrixOption = {
          url: url,
          mainTableName: this.$route.params.tableName,
          tableName : this.options.tableName,
          mainTableValue: {ID: this.$route.params.itemId},
          formDataKey: formKey,
          fc: true
        }
        this.matrixModal = true
      },
      async apiCodeCheck(params) {
        let productId = null
        let skuId = null
        try {
          const { data } = await network.post('/p/c/drp/validateProduct', params)
          if (data.code === 0 && data.data && data.data.productId) {
            productId = data.data.productId
          }
          if (data.code === 0 && data.data && data.data.skuId) {
            skuId = data.data.skuId
          }
        } catch {}
        
        return { productId, skuId }
      },
      async apiInputScan(url, params, type) {
        try {
          const { data } = await network.post(url, params)
          if (data.code === 0) {
            if (type === 'add') {
              const { tableName, tableId } = this.$route.params
              window.parent.R3.store.commit('global/tabOpen', {
                type: 'tableDetailVertical'||'V',
                tableName,
                tableId,
                id: data.data.objId
              })
            } else {
              window.__drpYunqueMatrixRefresh()
            }
          }
        } catch {}
      },
      handleModalCancel() {

      },
      handleRefreshMainData() {
        this.matrixModal = false
        window.__drpYunqueMatrixRefresh()
      },
      handleCloseMatrix() {
        this.matrixModal = false
      }
    }
  };
</script>
<style lang='less'>
  
</style>