<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible.sync="customerReturnOrderDialogFlag"
    :title="title"
    :close-on-click-modal="false"
    width="70%"
    :before-close="cancel">
    <el-card shadow="never" v-loading="loading">
      <div class="switch">
        <div class="switch_left">
          <ul>
            <li
              v-for="item in tabOptions"
              :key="item.key"
              :class="{ active: activeComp == item.key }"
              @click="activeComp = item.key"
            >
              {{ item.name }}
            </li>
          </ul>
        </div>
      </div>
      <el-form
        v-if="activeComp!=='bpm'"
        :rules="rules"
        ref="formRef"
        :model="form">
        <el-form-item>

        </el-form-item>
        <header-title title="退货物品明细" size="16px"></header-title>

        <ele-pro-table
          ref="table"
          :needPage="false"
          :columns="columns"
          :toolkit="[]"
          :datasource="form.detailList"
          cache-key="customerReturnOrderDialog"
          class="time-form"
        >
          <!-- 表头工具栏 -->
          <template v-slot:toolbar>
            <el-button
              size="small"
              type="primary"
              icon="el-icon-plus"
              class="ele-btn-icon"
              @click="handleSelectGoods"
              v-if="dialogType!=='view'&&taskDefinitionKey=='stater'"

            >
              选择退货物品
            </el-button>
          </template>
          <template v-slot:action="{ row,$index }">
            <el-popconfirm
              class="ele-action"
              title="确定要删除吗？"
              @confirm="remove(row,$index)">
              <template v-slot:reference>
                <el-link type="danger" :underline="false" icon="el-icon-delete">
                  删除
                </el-link>
              </template>
            </el-popconfirm>
          </template>


          <template v-slot:packageCount="{ row,$index }">
            <el-form-item
              :prop="'detailList.'+$index+'.packageCount'"
              :rules="{required:row.outboundType!=2?true:false,trigger:'blur',message:'请输入'}">
              <el-input v-if="activeComp == taskDefinitionKey&&dialogType!=='view'&&row.outboundType!=2"
                        v-model="row.packageCount"></el-input>
              <div v-else>{{ row.packageCount }}</div>
            </el-form-item>
          </template>

          <template v-slot:measurementCount="{ row,$index }">
            <el-form-item
              :prop="'detailList.'+$index+'.measurementCount'"
              :rules="{required:true,trigger:'blur',message:'请输入'}">
              <el-input v-if="activeComp == taskDefinitionKey&&dialogType!=='view'"
                        v-model="row.measurementCount"></el-input>
              <div v-else>{{ row.measurementCount }}</div>
            </el-form-item>
          </template>

          <template v-slot:weight="{ row,$index }">
            <el-form-item
              :prop="'detailList.'+$index+'.weight'"
              :rules="{required:true,trigger:'blur',message:'请输入'}">
              <el-input v-if="activeComp == taskDefinitionKey&&dialogType!=='view'"
                        v-model="row.weight"></el-input>
              <div v-else>{{ row.weight }}</div>
            </el-form-item>
          </template>

          <template v-slot:carveCode="{ row,$index }">
            <el-form-item
              :prop="'detailList.'+$index+'.carveCode'"
              :rules="{required:true,trigger:'blur',message:'请输入'}">
              <el-input v-if="activeComp == taskDefinitionKey&&dialogType!=='view'"
                        v-model="row.carveCode"></el-input>
              <div v-else>{{ row.carveCode }}</div>
            </el-form-item>
          </template>

          <!--  ///  发起人展示字段 -->
          <template v-slot:reason="{ row,$index }">
            <el-form-item
              :prop="'detailList.'+$index+'.reason'"
              :rules="{required:true,trigger:'blur',message:'请输入'}">
              <el-input v-if="activeComp == taskDefinitionKey&&dialogType!=='view'"
                        v-model="row.reason"></el-input>
              <div v-else>{{ row.reason }}</div>
            </el-form-item>
          </template>
          <template v-slot:feedbackDate="{ row,$index }">
            <el-form-item
              :prop="'detailList.'+$index+'.feedbackDate'"
              :rules="{required:true,trigger:'change',message:'请选择'}"
            >
              <el-date-picker
                v-if="activeComp == taskDefinitionKey&&dialogType!=='view'"
                v-model="row.feedbackDate"
                style="width: 100%"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期">
              </el-date-picker>
              <div v-else>{{ row.feedbackDate }}</div>
            </el-form-item>

          </template>
          <template v-slot:sendDate="{ row,$index }">
            <el-form-item
              :prop="'detailList.'+$index+'.sendDate'"
              :rules="{required:true,trigger:'change',message:'请选择'}"
            >
              <el-date-picker
                v-if="activeComp == taskDefinitionKey&&dialogType!=='view'"
                v-model="row.sendDate"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
              <div v-else>{{ row.sendDate }}</div>
            </el-form-item>

          </template>
          <!--////-->
        </ele-pro-table>
      </el-form>
      <!--      流程详情-->
      <bpmDetail v-if="activeComp==='bpm'&& form.processInstanceId" :id="form.processInstanceId"></bpmDetail>
    </el-card>
    <div slot="footer" v-if="activeComp == taskDefinitionKey&&dialogType!=='view'">
      <el-button type="primary" @click="handleSubmit('save')">保存</el-button>
      <el-button type="primary" @click="handleSubmit('sub')">提交</el-button>
      <el-button type="info" @click="cancel">关闭</el-button>
    </div>
    <!--出库详情-->
    <outbound-details-dialog v-if="outboundDetailsDialogFlag" ref="outboundDetailsDialogRef"
                             :outboundDetailsDialogFlag.sync="outboundDetailsDialogFlag"
                             @saveDate="saveDate"></outbound-details-dialog>
    <head-list ref="headRef" @changeParent="changeHead"></head-list>
  </ele-modal>
</template>


<script>

import outboundDetailsDialog from './outboundDetailsDialog.vue'
import headList from "@/views/saleManage/businessOpportunity/components/headList.vue";
import {
  getOutInBySourceBizNoAPI,
  saleReturnGetByIdAPI,
  saleReturnSaveAPI,
  saleReturnUpdateAPI,
  salesOrderReturnSubmit
} from "@/api/saleManage/returnGoods";
import {deepClone} from "@/utils";
import bpmDetail from "@/views/bpm/processInstance/detail.vue";


export default {
  name: "customerReturnOrderDialog",
  props: {
    taskDefinitionKey: {
      type: String,
      default: 'stater',
    },
    customerReturnOrderDialogFlag: {
      type: Boolean,
      default: false,
    }
  },
  components: {bpmDetail, outboundDetailsDialog, headList},
  data() {
    return {
      title: '客户退货处理单',
      dialogType: 'add',
      tabOptions: [
        {key: 'stater', name: '发起人申请'},
        {key: 'bpm', name: '流程详情'},
      ],
      activeComp: '',
      outboundDetailsDialogFlag: false,
      loading: false,
      warehousingMaterialList: [],
      materialCodeReqList: [],
      metaList: [],
      currentRow: {},
      form: {
        detailList: [],
      },
      rules: {}

    }
  },
  computed: {
    columns() {
      let basicFields = [
        {
          columnKey: 'action',
          label: '操作',
          width: 120,
          align: 'center',
          resizable: false,
          slot: 'action',
          fixed: 'right',
          showOverflowTooltip: true,

        },
        {
          width: 45,
          type: 'index',
          columnKey: 'index',
          align: 'center',
          fixed: 'left'
        },
        {
          minWidth: 120,
          prop: 'name',
          label: '名称',
          align: 'center',
          slot: 'name'
        },
        {
          minWidth: 120,
          prop: 'categoryCode',
          label: '编码',
          align: 'center',
          slot: 'categoryCode'
        },
        // {
        //   minWidth: 120,
        //   prop: 'modelType',
        //   label: '型号',
        //   align: 'center',
        //   slot: 'modelType'
        // },
        {
          minWidth: 120,
          prop: 'specification',
          label: '规格',
          align: 'center',
          slot: 'specification'
        },
        {
          minWidth: 80,
          prop: 'packageCount',
          label: '包装数量',
          align: 'center',
          slot: 'packageCount',
          headerSlot: 'headerPackingCount'
        },
        {
          minWidth: 80,
          prop: 'packingUnit',
          label: '包装单位',
          align: 'center',
          slot: 'packingUnit'
        },
        {
          minWidth: 80,
          prop: 'measurementCount',
          label: '计量数量',
          align: 'center',
          slot: 'measurementCount',
          headerSlot: 'headerCount'
        },
        {
          minWidth: 80,
          prop: 'measuringUnit',
          label: '计量单位',
          align: 'center',
          slot: 'measuringUnit'
        },
        {
          minWidth: 80,
          prop: 'weight',
          label: '重量',
          align: 'center',
          slot: 'weight',
          headerSlot: 'headerWeight'
        },
        {
          minWidth: 80,
          prop: 'weightUtil',
          label: '重量单位',
          align: 'center',
          slot: 'weightUtil'
        },
        {
          minWidth: 80,
          prop: 'carveCode',
          label: '刻码',
          slot: 'carveCode',
          align: 'center',
          headerSlot: 'headerEngrave'
        },
      ]
      let processNodes = {
        //发起人
        stater: [
          {
            minWidth: 140,
            prop: 'reason',
            label: '客户退货理由',
            align: 'center',
            slot: 'reason',
            headerSlot: 'headerReason'
          },
          {
            minWidth: 180,
            prop: 'feedbackDate',
            label: '客户反馈日期',
            align: 'center',
            slot: 'feedbackDate'
          },
          {
            minWidth: 180,
            prop: 'sendDate',
            label: '客户发出日期',
            slot: 'sendDate',
            align: 'center',
            headerSlot: 'headerSendDate'
          },
        ],
        //仓管入库
        storeman: [
          {
            minWidth: 140,
            prop: 'ifPackageOk',
            label: '包装完好与否',
            align: 'center',
            slot: 'ifPackageOk',
            headerSlot: 'headerIfPackageOk'
          },
          {
            minWidth: 140,
            prop: 'unpackUserName',
            label: '责任人',
            align: 'center',
            slot: 'unpackUserName'
          }
        ],
      }
      processNodes[this.taskDefinitionKey] && basicFields.push(...processNodes[this.taskDefinitionKey])
      this.activeComp = this.taskDefinitionKey
      return basicFields
    }
  },
  methods: {
    //删除
    remove(row, index) {
      this.form.detailList.splice(index, 1)
    },
    //初始化
    init(type, row = {}) {
      this.dialogType = type
      this.currentRow = row
      if (type !== 'add') {
        this.getReturnInfo(row)
      }
    },
    //获取详情
    async getReturnInfo(row) {
      this.form = await saleReturnGetByIdAPI(row.handleReceiptId)
      //拼接信息
      const data = await getOutInBySourceBizNoAPI(row.sendNo)
      this.infoData = deepClone(data)


      //出库物料明细
      this.warehousingMaterialList = this.infoData?.outInDetailVOList || []
      //出库包装明细
      if (this.warehousingMaterialList.length) {
        this.materialCodeReqList = []
        this.warehousingMaterialList.forEach(item => {
          if (item.outInDetailRecordVOList?.length) {
            item.outInDetailRecordVOList = item.outInDetailRecordVOList.map(i => {
              return {
                ...i,
                outInCode: this.infoData.bizNo,
                outInId: item.outInId,
                measurementCount: i.totalCount,
                outboundDetailId: i.id,
                outboundType: 1,
                packageCount: i.packingCount,
                packingUnit: i.packingUnit,
                weight: i.weight,
                specification: item.specification,
                name: i.name,
                carveCode: i.carveCode,
                categoryCode: i.categoryCode,
                id: ''
              }
            })
            this.materialCodeReqList.push(...item.outInDetailRecordVOList)
          }
        })
        //出库物料明细
        if (this.materialCodeReqList.length) {
          this.metaList = []
          this.materialCodeReqList.forEach(item => {
            if (item.outInDetailRecordMaterialDetailVOList?.length) {
              item.outInDetailRecordMaterialDetailVOList = item.outInDetailRecordMaterialDetailVOList.map(i => {
                return {
                  ...i,
                  outInId: item.outInId,
                  outInCode: item.outInCode,
                  measurementCount: 1,
                  outboundDetailId: i.id,
                  outboundType: 2,
                  packageCount: i.packingCount,
                  packingUnit: i.packingUnit,
                  weight: i.weight,
                  weightUtil: i.weightUnit,
                  specification: item.specification,
                  categoryCode: i.assetCode,
                  name: i.assetName,
                  carveCode: i.carveCode,
                  id: ''
                }
              })
              this.metaList.push(...item.outInDetailRecordMaterialDetailVOList)
            }
          })
        }
      }

      this.form.detailList.forEach(item => {
        if (item.outboundType == 1) {
          let find = this.materialCodeReqList.find(i => i.outboundDetailId == item.outboundDetailId) || {}
          item.name = find.name
          item.categoryCode = find.categoryCode
          item.specification = find.specification
          item.weightUtil = find.weightUtil
          item.packingUnit = find.packingUnit
          item.measuringUnit = find.measuringUnit
        } else {
          let find = this.metaList.find(i => i.outboundDetailId == item.outboundDetailId) || {}
          item.name = find.name
          item.categoryCode = find.categoryCode
          item.specification = find.specification
          item.weightUtil = find.weightUtil
          item.packingUnit = find.packingUnit
          item.measuringUnit = find.measuringUnit
        }
      })

      this.$nextTick(() => {
        this.$refs.table.reRenderTable()
      })


    },
    handleSelectGoods() {
      this.outboundDetailsDialogFlag = true
      this.$nextTick(() => {
        this.$refs.outboundDetailsDialogRef.init(this.currentRow )
      })
    },
    //选择退货信息回调
    saveDate(data) {
      this.form.detailList.push(...data)
    },
    //选择负责人
    handHead(row, index) {
      let item = {
        id: row.unpackUserId
      };
      this.$refs.headRef.open(item, index);
    },
    //选择负责人回调
    changeHead(obj, index) {
      this.$set(this.form.detailList[index], 'unpackUserId', obj.id);
      this.$set(this.form.detailList[index], 'unpackUserName', obj.name);
    },
    cancel() {
      this.$emit('update:customerReturnOrderDialogFlag', false)
    },
    async handleSubmit(type) {

      await this.$refs.formRef.validate(async validate => {
        if (!validate) return this.$message.warning('有必填项未填，请检查')
        let params = {
          detailList: this.form.detailList.map(i => {
            return {
              outInId: i.outInId,
              outInCode: i.outInCode,
              measurementCount: i.measurementCount,
              measurementUnit: i.measuringUnit,
              outboundDetailId: i.outboundDetailId,
              outboundType: i.outboundType,
              productName: i.name,
              productCode: i.categoryCode,
              packageCount: i.packageCount,
              packingUnit: i.packingUnit,
              weight: i.weight,
              weightUtil: i.weightUtil,
              specification: i.specification,
              modelType: i.modelType,
              carveCode: i.carveCode,
              reason: i.reason,
              sendDate: i.sendDate,
              feedbackDate: i.feedbackDate,
              id: i.id
            }
          }),
          returnRecordId: this.currentRow.id,
          id: this.currentRow.handleReceiptId
        }
        let api = this.dialogType == 'add' ? saleReturnSaveAPI : saleReturnUpdateAPI
        const data = await api(params)
        console.log(data, '===');
        this.$message.success('操作成功')
        if (type == 'sub') {
          await salesOrderReturnSubmit({businessId: data})

        }
        this.cancel()
      })


    },
  }
}
</script>
<style scoped lang="scss">

</style>
