<template>
  <div>
    <zj-form-container ref="formRef" :form-data="formData" :form-rules="formRules">
      <zj-form-module title="调拨单" :form-data="formData" :form-items="formItems" label-width="100px" :column="3" />
      <zj-form-module title="调拨单明细" :form-items="detailData" label-width="0" :column="3" />
      <zj-form-module
        v-if="moduleType === 2"
        title="物流费用"
        :form-items="formLogisticsData"
        label-width="0"
        :column="3"
      />
      <zj-form-module
        v-if="moduleType === 3"
        title="审核信息"
        :form-data="formData"
        :form-items="formExamine"
        label-width="100px"
        :column="3"
      />
    </zj-form-container>
    <el-dialog title="添加产品" :visible.sync="visible" width="60%" :append-to-body="true" @close="visible = false">
      <div style="height: 600px">
        <template-page
          ref="pageRef"
          style="height: 100%"
          :get-list="getList"
          :column-parsing="columnParsing"
          :table-attributes="tableAttributes"
          :table-events="tableEvents"
        />
      </div>
      <span slot="footer">
        <el-button type="primary" @click="handleAddData">提交</el-button>
      </span>
    </el-dialog>
    <!-- 新增 -->
    <div v-if="!comDisabled">
      <template v-if="moduleType === 1">
        <el-button type="primary" size="mini" @click="onSubmit('WAIT')">提交</el-button>
        <el-button size="mini" @click="onSubmit('SAVE')">保存</el-button>
      </template>
      <template v-else>
        <el-button type="primary" size="mini" @click="onSubmit">编辑</el-button>
      </template>
      <el-button size="mini" @click="onReset">重置</el-button>
    </div>
    <!-- 审核 /详情-->
    <div v-if="moduleType === 3 || moduleType === 2">
      <el-button v-if="moduleType === 3" type="primary" size="mini" @click="onExamine('OK')">同意</el-button>
      <el-button size="mini" @click="onInvoice('SAVE')">撤回</el-button>
    </div>
  </div>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import { getcustomerFrontList } from '@/api/stock'
import { getListCostBillV2 } from '@/api/logisticsBill'

import { getStagecustomerListV2, getDealerListV2 } from '@/api/basic_data/dealer'
import {
  addCustomerTransfer,
  updateCustomerTransfer,
  getCustomerTransferDetail,
  examineCustomerTransfer,
  invoiceCustomerTransfer
} from '@/api/transferOrder'
import { mapGetters } from 'vuex'

export default {
  components: { TemplatePage },
  props: {
    edit: {
      type: Boolean,
      default: false
    },
    detailsId: {
      type: String,
      default: null
    },
    moduleType: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      visible: false,
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true,
        selectable: this.selectable
      }, // 关闭新增弹窗

      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      itemTableEvents: { 'selection-change': this.itemSelectionChange },
      defaultTableAttributes: {
        border: true,
        headerCellClassName: 'headerRowColor',
        size: 'mini',
        'summary-method': this.$getSummaries,
        'show-summary': true
      },
      recordSelected: [],
      formData: {
        customerNumber: '',
        customerName: '',
        transferTime: '',
        createBy: '',
        transferCustomerNumber: '',
        transferCustomerName: '',
        stockType: '',
        createTime: '',
        notes: ''
      },
      formRules: {
        customerNumber: [{ required: true, message: '请输入', trigger: 'blur' }],
        customerName: [{ required: true, message: '请输入', trigger: 'blur' }],
        transferTime: [{ required: true, message: '请选择', trigger: 'change' }],
        transferCustomerNumber: [{ required: true, message: '请输入', trigger: 'blur' }],
        transferCustomerName: [{ required: true, message: '请选择', trigger: 'change' }],
        stockType: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      fileType: ['word', 'excel', 'ppt', 'pdf'],
      fileList: [],
      fileList2: [],
      srcList: [],
      dict: [],
      mainContractList: [],
      serviceProviderList: [],
      filetype: [],
      authList: [],
      selectData: [],
      itemRecordSelected: [],
      sonCustomerList: [],
      logisticsData: [],
      sonCustomerNumberList: [],
      sonCustomerNameList: [],
      setDisabled: {
        disabledDate: time => {
          return time.getTime() < new Date() - 24 * 3600 * 1000
        }
      }
    }
  },
  computed: {
    ...mapGetters(['customerNumber', 'customerName']),
    comDisabled() {
      // 禁止
      return !!~[2, 3].indexOf(this.moduleType || 1)
    },
    formItems() {
      return [
        {
          name: 'el-input',
          md: 6,
          attributes: { disabled: true, placeholder: '请输入' },
          formItemAttributes: { label: '商家编号', prop: 'customerNumber' }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: { disabled: true, placeholder: '请输入' },
          formItemAttributes: { label: '商家名称', prop: 'customerName' }
        },
        {
          name: 'el-date-picker',
          md: 6,
          attributes: {
            type: 'datetime',
            style: { width: '100%' },
            placeholder: '选择日期时间',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            disabled: this.comDisabled,
            pickerOptions: this.setDisabled

          },
          formItemAttributes: { label: '调整日期', prop: 'transferTime' }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: { disabled: true, placeholder: '系统自动生成' },
          formItemAttributes: { label: '制单人', prop: 'createBy' }
        },
        {
          name: 'el-select',
          options: this.sonCustomerNumberList,
          events: {
            change: (e) => this.handleChange(e, 'transferCustomerNumber')
          },
          md: 6,
          attributes: {
            clearable: true,
            filterable: true,
            disabled: this.comDisabled
          },
          formItemAttributes: { label: '商家编号', prop: 'transferCustomerNumber' }
        },
        {
          name: 'el-select',
          options: this.sonCustomerNameList,
          md: 6,
          events: {
            change: (e) => this.handleChange(e, 'transferCustomerName')
          },
          attributes: {
            clearable: true,
            filterable: true,
            disabled: this.comDisabled
          },
          formItemAttributes: { label: '商家名称', prop: 'transferCustomerName' }
        },
        {
          name: 'el-select',
          md: 6,
          options: [
            { label: '嘉贤前置仓', value: 'JIAXIAN' }
            // { label: '商家仓', value: 'SHANGJIA' }
          ],
          attributes: { disabled: this.comDisabled, placeholder: '请输入' },
          formItemAttributes: { label: '调拨仓库', prop: 'stockType' }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: { disabled: true, placeholder: '系统自动生成' },
          formItemAttributes: { label: '制单时间', prop: 'createTime' }
        },
        {
          name: 'el-input',
          md: 24,
          attributes: { type: 'textarea', style: { width: '100%' }, disabled: this.comDisabled, placeholder: '请输入' },
          formItemAttributes: { label: '备注', prop: 'notes' }
        }
      ]
    },
    formExamine() {
      return [
        {
          name: 'el-input',
          md: 6,
          attributes: { disabled: true },
          formItemAttributes: { label: '审核人', prop: 'approvalName' }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: { disabled: true },
          formItemAttributes: { label: '审核时间', prop: 'approvalTime' }
        },
        {
          name: 'el-input',
          md: 24,
          attributes: { type: 'textarea', style: { width: '100%' }, placeholder: '请输入' },
          formItemAttributes: { label: '备注', prop: 'approvalRemark' }
        }
      ]
    },
    columns() {
      return [
        {
          columnAttributes: {
            label: '产品名称',
            prop: 'materialName'
          }
        },
        {
          columnAttributes: {
            label: '产品编码',
            prop: 'materialOldNumber'
          }
        },
        {
          columnAttributes: {
            label: '规格型号',
            prop: 'specification',
            width: 300
          }
        },
        ...[this.moduleType === 1 ? {
          columnAttributes: {
            label: '可调拨库存数',
            prop: 'frontStockNum'
          }
        } : {}],
        {
          columnAttributes: {
            label: '调拨数量',
            prop: 'qty'
          },
          render: (h, { column, row, index }) => {
            return (
              <div style='margin:0 20px'>
                <el-input
                  type='number'
                  disabled={this.comDisabled}
                  value={row.qty}
                  onInput={e => (row.qty = e)}
                  placeholder='调拨数量'
                  size='mini'
                ></el-input>
              </div>
            )
          }
        },
        {
          columnAttributes: {
            label: '备注',
            prop: 'notes'
          },
          render: (h, { column, row, index }) => {
            return (
              <el-input
                type='text'
                value={row.notes}
                disabled={this.comDisabled}
                onInput={e => (row.notes = e)}
                placeholder='备注'
                size='mini'
              ></el-input>
            )
          }
        },
        {
          columnAttributes: {
            label: '调拨仓库',
            prop: 'stockName'
          }
        },
        {
          columnAttributes: {
            label: '操作',
            prop: ''
          },
          render: (h, { column, row, index }) => {
            return (
              <div>
                {!this.comDisabled ? (
                  <el-button
                    type='text'
                    size='default'
                    onClick={() => {
                      this.handleDel(index)
                    }}
                  >
                    删除
                  </el-button>
                ) : null}
              </div>
            )
          }
        }
      ]
    },
    detailData() {
      return [
        ...[
          !this.comDisabled
            ? {
              name: 'slot-component',
              md: 24,
              attributes: { disabled: false },
              formItemAttributes: { label: '', prop: '' },
              render: (h, { props, onInput }) => {
                return (
                  <div>
                    <el-button
                      size='mini'
                      onClick={() => {
                        this.visible = true
                        this.recordSelected = []
                      }}
                    >
                        添加
                    </el-button>
                    <el-button size='mini' onClick={() => this.handleAllDel()}>
                        删除
                    </el-button>
                  </div>
                )
              }
            }
            : {}
        ],
        {
          name: 'slot-component',
          md: 24,
          attributes: { disabled: false },
          formItemAttributes: { label: '', prop: '' },
          render: (h, { props, onInput }) => {
            var { value } = props
            return (
              <zj-table
                isDrop={true}
                columns={this.columns}
                tableData={this.selectData}
                tableAttributes={{ border: true, selectColumn: !this.comDisabled }}
                tableEvents={this.itemTableEvents}
              ></zj-table>
            )
          }
        }
      ]
    },
    formLogistics() {
      return [
        {
          columnAttributes: {
            label: '序号',
            prop: 'materialName',
            type: 'index'
          }
        },
        {
          columnAttributes: {
            label: '结算状态',
            prop: 'materialName'
          }
        },
        {
          columnAttributes: {
            label: '调拨单号',
            prop: 'materialName'
          }
        },
        {
          columnAttributes: {
            label: '嘉贤单据号',
            prop: 'materialName'
          }
        },
        {
          columnAttributes: {
            label: '存货编码',
            prop: 'materialName'
          }
        },
        {
          columnAttributes: {
            label: '物料代码',
            prop: 'materialName'
          }
        },
        {
          columnAttributes: {
            label: '产品名称',
            prop: 'materialName'
          }
        },
        {
          columnAttributes: {
            label: '规格型号',
            prop: 'materialName'
          }
        },
        {
          columnAttributes: {
            label: '单价',
            prop: 'materialName'
          }
        },
        {
          columnAttributes: {
            label: '数量',
            prop: 'materialName'
          }
        },
        {
          columnAttributes: {
            label: '物流费用',
            prop: 'materialName'
          }
        },
        {
          columnAttributes: {
            label: '仓储费用',
            prop: 'materialName'
          }
        },
        {
          columnAttributes: {
            label: '合计费用',
            prop: 'materialName'
          }
        },
        {
          columnAttributes: {
            label: '对账人',
            prop: 'materialName'
          }
        },
        {
          columnAttributes: {
            label: '对账日期',
            prop: 'materialName'
          }
        },
        {
          columnAttributes: {
            label: '结算人',
            prop: 'materialName'
          }
        },
        {
          columnAttributes: {
            label: '结算日期',
            prop: 'materialName'
          }
        }
      ]
    },
    formLogisticsData() {
      return [
        {
          name: 'slot-component',
          md: 24,
          attributes: { disabled: false },
          formItemAttributes: { label: '', prop: '' },
          render: (h, { props, onInput }) => {
            var { value } = props
            return (
              <zj-table
                tableAttributes={{ ...this.defaultTableAttributes }}
                isDrop={true}
                columns={this.formLogistics}
                tableData={this.logisticsData}
                tableEvents={this.itemTableEvents}
              ></zj-table>
            )
          }
        }
      ]
    }
  },
  mounted() {
    this.getStagecustomerListV2()
    if (this.detailsId) {
      getCustomerTransferDetail({ id: this.detailsId }).then(res => {
        this.formData = res.data
        this.selectData = res.data.orders.map(k => {
          k.disabledId = k.customerStockId
          k.stockName = '嘉贤前置仓'

          return k
        })
        delete this.formData.orders
      })
    }
    if (this.detailsId && this.moduleType === 2) {
      getListCostBillV2({
        pageNum: 1,
        pageSize: -1,
        params: [
          {
            param: 'order_code',
            compare: '=',
            value: this.detailsId
          }
        ]
      }).then(res => {
        res.data.records.forEach(item => {
          item.sums1 = ['orderHasSendQty', 'subsidyCoefficient', 'unloadUpstairsCoefficient', 'coefficient']
          item.sums2 = ['cost', 'unitPrice', 'totalCost', 'allowanceCost']
        })
        this.logisticsData = res.data.records
      })
    }
  },
  methods: {
    // 列表请求函数
    getList(...p) {
      this.recordSelected = []
      return getcustomerFrontList(...p)
    },
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    }, // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    itemSelectionChange(data) {
      this.itemRecordSelected = data
    },
    selectable(row, index) {
      if (this.selectData.length) {
        for (let j = 0; j < this.selectData.length; j++) {
          if (row.id === this.selectData[j].disabledId) {
            this.$set(row, 'disabledId', this.selectData[j].disabledId)
          }
        }
      }

      if (!row.disabledId) {
        return true
      } else {
        return false
      }
    },
    getStagecustomerListV2() {
      this.formData.customerNumber = this.customerNumber
      this.formData.customerName = this.customerName
      getStagecustomerListV2({
        pageNum: 1,
        pageSize: -1,
        params: [
          {
            param: 'a.higher_prant_number',
            compare: '=',
            value: this.customerNumber || ''
          }
        ]
      }).then(res => {
        this.sonCustomerList = res.data.records
        this.sonCustomerNameList = res.data.records.map(k => {
          return {
            label: k.name,
            value: k.id
          }
        })
        this.sonCustomerNumberList = res.data.records.map(k => {
          return {
            label: k.number,
            value: k.id
          }
        })
      })
    },
    handleAddData() {
      this.selectData = [...this.selectData, ...this.recordSelected]
      for (let i = 0; i < this.$refs.pageRef.$children[0].tableData.length; i++) {
        for (let j = 0; j < this.selectData.length; j++) {
          if (this.$refs.pageRef.$children[0].tableData[i].id == this.selectData[j].id) {
            this.$set(this.$refs.pageRef.$children[0].tableData[i], 'disabledId', this.selectData[j].id)
          }
        }
      }
      this.selectData = this.selectData.map(k => {
        return {
          materialCode: k.materialCode,
          materialId: '',
          materialName: k.materialName,
          materialOldNumber: k.materialOldNumber,
          notes: '',
          qty: 0,
          frontStockNum: k.frontStockNum,
          specification: k.specification,
          disabledId: k.disabledId,
          stockName: '嘉贤前置仓',
          customerStockId: k.disabledId
        }
      })
      this.visible = false
      this.handleClearSelection()
    },
    handleAllDel() {
      if (this.itemRecordSelected.length) {
        if (this.$refs.pageRef) {
          for (let i = 0; i < this.$refs.pageRef.$children[0].tableData.length; i++) {
            for (let j = 0; j < this.itemRecordSelected.length; j++) {
              if (this.$refs.pageRef.$children[0].tableData[i].id === this.itemRecordSelected[j].disabledId) {
                this.$set(this.$refs.pageRef.$children[0].tableData[i], 'disabledId', null)
              }
            }
          }
        }
        for (let j = 0; j < this.itemRecordSelected.length; j++) {
          for (let k = 0; k < this.selectData.length; k++) {
            if (this.selectData[k].disabledId === this.itemRecordSelected[j].disabledId) {
              this.selectData.splice(k, 1)
            }
          }
        }
        this.handleClearSelection()
      } else {
        this.$errorMsg('请选择删除项')
      }
    },
    handleDel(index) {
      if (this.$refs.pageRef) {
        for (let i = 0; i < this.$refs.pageRef.$children[0].tableData.length; i++) {
          if (this.$refs.pageRef.$children[0].tableData[i].id === this.selectData[index].disabledId) {
            this.$set(this.$refs.pageRef.$children[0].tableData[i], 'disabledId', null)
          }
        }
      }
      this.selectData.splice(index, 1)
      this.handleClearSelection()
    },
    handleClearSelection() {
      this.recordSelected = []
      this.$refs.pageRef &&
        this.$refs.pageRef.$children[0].$children[0].$children[2].$children[0].$children[0].clearSelection()
    },
    handleChange(e, type) {
      if (e) {
        if (type === 'transferCustomerNumber') {
          this.formData.transferCustomerName = this.sonCustomerList.find(k => k.id === e).name
        } else {
          this.formData.transferCustomerNumber = this.sonCustomerList.find(k => k.id === e).number
        }
      } else {
        this.formData.transferCustomerNumber = ''
        this.formData.transferCustomerName = ''
      }
    },
    handlerefreshList() {
      this.$emit('refresh')
      this.onClose()
    },
    onClose() {
      this.formData = {}
      this.selectData = []
      this.$emit('close')
    },
    onReset() {
      this.$refs.formRef.resetFields()
      this.selectData = []
    },
    onSubmit(type) {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          const params = {
            ...this.formData,
            orders: this.selectData
          }
          if (this.moduleType === 1) {
            params.status = type
            addCustomerTransfer(params).then(res => {
              this.$successMsg(type === 'SAVE' ? '保存成功' : '新增成功')
              this.handlerefreshList()
            })
          } else {
            updateCustomerTransfer(params).then(res => {
              this.$successMsg('编辑成功')
              this.handlerefreshList()
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    onExamine(type) {
      examineCustomerTransfer({
        id: this.detailsId,
        status: type
      }).then(res => {
        this.$successMsg('审核成功')
        this.handlerefreshList()
      })
    },
    onInvoice(type) {
      invoiceCustomerTransfer({
        id: this.detailsId,
        status: type
      }).then(res => {
        this.$successMsg('撤回成功')
        this.handlerefreshList()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.header1style {
  text-align: right;
  font-size: 12px;
  color: red;
  line-height: 18px;
}
</style>
