<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible.sync="addOrEditDialogFlag"
    :title="title"
    :close-on-click-modal="false"
    width="70%"
    :append-to-body="false"
    :before-close="cancel">
    <el-form
      :rules="rules"
      ref="formRef"
      :model="form">


      <el-row style="margin-bottom: 10px">
        <el-col :span="6">
          <el-descriptions class="margin-top" :column="3" size="mini" border>
            <el-descriptions-item>
              <template slot="label">
                <div class="is-required">
                  退货单
                </div>
              </template>
              <el-form-item prop="returnNo">
                <el-input
                  clearable
                  v-model="form.returnNo"
                  @click.native="handleOrderBtn"
                  placeholder="请选择"/>
              </el-form-item>

            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>

      <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'&&form.returnNo"
          >
            选择退货物品
          </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="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="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="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="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="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="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="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>
    <div slot="footer" v-if="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>
    <return-order-dialog :returnOrderDialogFlag.sync="returnOrderDialogFlag" v-if="returnOrderDialogFlag"
                         @changeParent="getReturnOrderInfo">
      ref="returnOrderDialogRef">
    </return-order-dialog>
  </ele-modal>
</template>


<script>

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


export default {
  name: "addOrEditDialog",
  props: {
    addOrEditDialogFlag: {
      type: Boolean,
      default: false,
    }
  },
  components: {
    fileUpload,
    outboundDetailsDialog,
    headList,
    returnOrderDialog
  },
  data() {
    return {
      title: '客户退货处理单',
      dialogType: 'add',
      activeComp: '',
      outboundDetailsDialogFlag: false,
      returnOrderDialogFlag: false,
      loading: false,
      warehousingMaterialList: [],
      materialCodeReqList: [],
      metaList: [],
      currentRow: {},
      form: {
        detailList: [],
        returnNo: '',
      },
      rules: {
        returnNo: {required: true, message: '请选择', trigger: 'change'}
      }

    }
  },
  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'
        },
        {
          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'
        },
      ]
      let processNodes = {
        //详情
        view: [
          {
            minWidth: 140,
            prop: 'ifPackageOk',
            label: '包装完好与否',
            align: 'center',
            slot: 'ifPackageOk',
            headerSlot: 'headerIfPackageOk'
          },
          {
            minWidth: 140,
            prop: 'unpackUserName',
            label: '拆包装责任人',
            align: 'center',
            slot: 'unpackUserName',
            headerSlot: 'headerUnpackUserName'
          },
          {
            minWidth: 250,
            prop: 'ifReasonMatch',
            label: '退货原因是否与退货信息一致',
            align: 'center',
            slot: 'ifReasonMatch',
            headerSlot: 'headerIfReasonMatch'
          },
          {
            minWidth: 140,
            prop: 'reason',
            label: '客户退货理由',
            align: 'center',
            slot: 'reason',
            headerSlot: 'headerReason'
          },
          {
            minWidth: 250,
            prop: 'unqualifiedReasonAnalysis',
            label: '不合格原因分析',
            align: 'center',
            slot: 'unqualifiedReasonAnalysis',
            headerSlot: 'headerUnqualifiedReasonAnalysis'
          },
          {
            minWidth: 250,
            prop: 'unqualifiedTypeName',
            label: '不合格类型',
            align: 'center',
            slot: 'unqualifiedTypeName',
            headerSlot: 'headerUnqualifiedType'
          },
          {
            minWidth: 250,
            prop: 'handleOpinion',
            label: '对不合格品的处理意见',
            align: 'center',
            slot: 'handleOpinion',
            headerSlot: 'headerHandleOpinion'
          },

          {
            minWidth: 130,
            prop: 'inOrOut',
            label: '内部或外部',
            align: 'center',
            slot: 'inOrOut',
            formatter: (_row, _column, cellValue) => {
              return _row.inOrOut == 1 ? '内部' : '外部';
            }
          },
          {
            minWidth: 250,
            prop: 'outerInfo',
            label: '外协单位',
            align: 'center',
            slot: 'outerInfo',
          },
          {
            minWidth: 250,
            prop: 'improveCorrect',
            label: '不合格原因是否改善到位',
            align: 'center',
            slot: 'improveCorrect',
            headerSlot: 'headerImproveCorrect'
          },
          {
            minWidth: 250,
            prop: 'improveOpinion',
            label: '对改善后产品处理意见',
            align: 'center',
            slot: 'improveOpinion',
            headerSlot: 'headerImproveOpinion'
          }
        ],
      }
      processNodes[this.dialogType] && basicFields.push(...processNodes[this.dialogType])
      return basicFields
    }
  },
  methods: {
    //删除
    remove(row, index) {
      this.form.detailList.splice(index, 1)
    },
    //初始化
    init(type, row = {}) {
      this.dialogType = type
      if (type !== 'add') {
        this.getReturnInfo(row)
      }
    },

    //获取详情
    async getReturnInfo(row) {
      this.form = await saleReturnGetByIdAPI(row.id)
      //拼接信息
      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()
      })
    },
    //选择退货单
    handleOrderBtn() {
      this.returnOrderDialogFlag = true
      // this.$nextTick(() => {
      //   this.$refs.returnOrderDialogRef.init()
      // })
    },
    //退货单
    getReturnOrderInfo(row) {
      this.form.returnNo = row.returnNo
      this.form.returnRecordId = row.id
      this.form.sendNo = row.sendNo
      this.form.detailList = []
    },
    //选择退货明细
    handleSelectGoods() {
      this.outboundDetailsDialogFlag = true
      this.$nextTick(() => {
        this.$refs.outboundDetailsDialogRef.init(this.form)
      })
    },
    //选择退货信息回调
    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:addOrEditDialogFlag', 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,
              packageCount: i.packageCount,
              packingUnit: i.packingUnit,
              weight: i.weight,
              weightUtil: i.weightUtil,
              specification: i.specification,
              modelType: i.modelType,
              carveCode: i.carveCode,
              productName: i.name,
              reason: i.reason,
              sendDate: i.sendDate,
              feedbackDate: i.feedbackDate,
              productCode: i.categoryCode,
              id: i.id
            }
          }),
          returnRecordId: this.form.returnRecordId,
          id: this.form.id
        }
        let api = this.dialogType == 'add' ? saleReturnSaveAPI : saleReturnUpdateAPI
        const data = await api(params)
        this.$message.success('操作成功')
        if (type == 'sub') {
          await salesOrderReturnSubmit({businessId: data})

        }
        this.$emit('done')
        this.cancel()
      })


    },
  }
}
</script>
<style scoped lang="scss">
:deep .el-form-item {
  margin-bottom: 0;
}
</style>
