<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="true"
    :before-close="cancel"
    :maxable="true"
    :resizable="true"
  >
    <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"
        :datasource="form.detailList"
        class="time-form"
        @columns-change="handleColumnChange"
        :cache-key="cacheKeyUrl"
      >
        <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:technologyRouteName="scope">
          <el-form-item
            :prop="'detailList.' + scope.$index + '.technologyRouteName'"
            :rules="{
              required: false,
              message: '请选择',
              trigger: 'change'
            }"
          >
            <el-input
              v-model="scope.row.technologyRouteName"
              placeholder="请选择"
              @click.native="openVersion(scope.$index)"
            ></el-input>
          </el-form-item>
        </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'">
            <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:technicalDrawings="scope">
          <el-form-item
            style="margin-bottom: 20px"
            :prop="'detailList.' + scope.$index + '.technicalDrawings'"
          >
            <fileMain v-model="scope.row.technicalDrawings"></fileMain>
          </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="选择日期"
              @change="listChange('feedbackDate', row.feedbackDate)"
            >
            </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="选择日期"
              @change="listChange('sendDate', row.sendDate)"
            >
            </el-date-picker>
            <div v-else>{{ row.sendDate }}</div>
          </el-form-item>
        </template>
        <template v-slot:headerReason="{ column }">
          <span class="is-required">{{ column.label }}</span>
        </template>
        <template v-slot:headerFeedbackDate="{ column }">
          <span class="is-required">{{ column.label }}</span>
        </template>
        <template v-slot:headerSendDate="{ column }">
          <span class="is-required">{{ column.label }}</span>
        </template>
      </ele-pro-table>
    </el-form>
    <div slot="footer" v-if="dialogType !== 'view'">
      <el-button type="primary" @click="handleSubmit('save')" v-click-once
        >保存</el-button
      >
      <el-button
        type="primary"
        v-if="isNeed_process_is_close"
        @click="handleSubmit('sub')"
        v-click-once
        >提交</el-button
      >
      <el-button type="info" @click="cancel">关闭</el-button>
    </div>

    <return-order-dialog
      :returnOrderDialogFlag.sync="returnOrderDialogFlag"
      v-if="returnOrderDialogFlag"
      @changeParent="getReturnOrderInfo"
    >
    </return-order-dialog>
    <process-submit-dialog
      :isNotNeedProcess="false"
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="reload"
    ></process-submit-dialog>
    <ProductionVersion
      ref="versionRefs"
      @changeProduct="changeProduct"
    ></ProductionVersion>
  </ele-modal>
</template>

<script>
  import returnOrderDialog from './returnOrderDialog.vue';
  import {
    getOutInBySourceBizNoAPI,
    saleReturnGetByIdAPI,
    saleReturnSaveAPI,
    saleReturnUpdateAPI,
    salesOrderReturnSubmit,
    getReturnSaleOrderrecordDetail
  } from '@/api/saleManage/returnGoods';
  import { deepClone } from '@/utils';
  import bpmDetail from '@/views/bpm/processInstance/detail.vue';
  // import fileUpload from '@/components/upload/fileUpload.vue';
  import { getDetail } from '@/api/saleManage/businessOpportunity';
  import processSubmitDialog from '@/BIZComponents/processSubmitDialog/processSubmitDialog.vue';
  import ProductionVersion from '@/components/ProductionVersion2/index.vue';
  // import fileMain from '@/components/addDoc/index.vue';
  import dictMixins from '@/mixins/dictMixins';
  import tabMixins from '@/mixins/tableColumnsMixin';

  export default {
    mixins: [dictMixins, tabMixins],
    name: 'addOrEditDialog',
    props: {
      addOrEditDialogFlag: {
        type: Boolean,
        default: false
      }
    },
    components: {
      processSubmitDialog,
      // fileUpload,
      // outboundDetailsDialog,
      // headList,
      returnOrderDialog,
      ProductionVersion,
      // fileMain
    },
    data() {
      return {
        cacheKeyUrl: 'eos-saleManage-customerReturnOrder-inventoryTable',
        title: '客户退货处理单',
        dialogType: 'add',
        activeComp: '',
        outboundDetailsDialogFlag: false,
        returnOrderDialogFlag: false,
        loading: false,
        processSubmitDialogFlag: false,
        warehousingMaterialList: [],
        materialCodeReqList: [],
        metaList: [],
        currentRow: {},
        detailList: [],
        form: {
          detailList: [],
          returnNo: ''
        },
        rules: {
          returnNo: { required: true, message: '请选择', trigger: 'change' }
        }
      };
    },
    computed: {
      columns() {
        let basicFields = [
          {
            width: 45,
            type: 'index',
            columnKey: 'index',
            align: 'center',
            fixed: 'left'
          },
          {
            minWidth: 160,
            prop: 'productCode',
            label: '编码',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 120,
            prop: 'productName',
            label: '名称',
            showOverflowTooltip: true,
            align: 'center'
          },

          {
            minWidth: 160,
            prop: 'batchNo',
            label: '批次号',
            showOverflowTooltip: true,
            slot: 'batchNo',
            align: 'center'
          },
          {
            minWidth: 160,
            prop: 'barcodes',
            label: '发货条码',
            showOverflowTooltip: true,
            slot: 'barcodes',
            align: 'center'
          },
          {
            minWidth: 120,
            prop: 'materielDesignation',
            label: '物料代号',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 120,
            prop: 'clientCode',
            label: '客户代号',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 120,
            prop: 'engrave',
            label: '刻码',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 160,
            prop: 'packageNo',
            align: 'center',
            label: '包装编码',
            showOverflowTooltip: true
          },
          {
            minWidth: 100,
            prop: 'packingQuantity',
            align: 'center',
            label: '包装数量',
            showOverflowTooltip: true
          },
          {
            minWidth: 120,
            prop: 'packingUnit',
            align: 'center',
            label: '包装单位',
            showOverflowTooltip: true
          },
          {
            minWidth: 100,
            prop: 'measurementCount',
            label: '计量数量',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 150,
            prop: 'measurementUnit',
            label: '计量单位',
            showOverflowTooltip: true,
            align: 'center'
          },
          // {
          //   width: 100,
          //   prop: 'singlePrice',
          //   label: '单价',
          //   slot: 'singlePrice',
          //   align: 'center'
          // },
          // {
          //   width: 100,
          //   prop: 'totalPrice',
          //   label: '合计',
          //   align: 'center'
          // },

          {
            minWidth: 80,
            prop: 'weight',
            label: '重量',
            slot: 'weight',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 100,
            prop: 'weightUnit',
            label: '重量单位',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            width: 240,
            prop: 'technologyRouteName',
            label: '工艺路线',
            slot: 'technologyRouteName',
            align: 'center'
          },
          {
            width: 240,
            prop: 'technicalDrawings',
            label: '技术图纸',
            slot: 'technicalDrawings',
            align: 'center'
          },
          {
            prop: 'provenance',
            label: '产地',
            slot: 'provenance',
            align: 'center',

            minWidth: 200,
            showOverflowTooltip: true,
            formatter: (row, column) => {
              return row.provenance && row.provenance.length
                ? row.provenance
                    .map((item) => this.getDictValue('产地', item))
                    .join(',')
                : '';
            }
          },
          {
            minWidth: 140,
            prop: 'reason',
            label: '客户退货理由',
            align: 'center',
            slot: 'reason',
            headerSlot: 'headerReason'
          },
          {
            minWidth: 180,
            prop: 'feedbackDate',
            label: '客户反馈日期',
            align: 'center',
            slot: 'feedbackDate',
            headerSlot: 'headerFeedbackDate'
          },
          {
            minWidth: 180,
            prop: 'sendDate',
            label: '客户发出日期',
            slot: 'sendDate',
            align: 'center',
            headerSlot: 'headerSendDate'
          }
        ];

        return basicFields;
      }
    },
    created() {
      this.requestDict('产地');
    },
    methods: {
      //删除
      remove(row, index) {
        this.form.detailList.splice(index, 1);
      },
      //初始化
      init(type, row = {}) {
        this.dialogType = type;
        if (type !== 'add') {
          this.getReturnInfo(row);
        } else {
          if (row?.id) {
            this.getReturnOrderInfo(row);
          }
        }
      },
      listChange(key, value) {
        this.form.detailList.forEach((item, index) => {
          if (!this.form.detailList[index][key]) {
            this.$set(this.form.detailList[index], key, value);
          }
        });
      },
      //工艺路线
      changeProduct(data, index) {
        this.$set(
          this.form.detailList[index],
          'technologyRouteName',
          data.name
        );
        this.$set(this.form.detailList[index], 'technologyRouteId', data.id);
      },
      openVersion(index) {
        this.$refs.versionRefs.open(index);
      },
      //获取详情
      async getReturnInfo(row) {
        this.form = await saleReturnGetByIdAPI(row.id);
        this.$nextTick(() => {
          this.$refs.table.reRenderTable();
        });
      },
      //获取退货单详情
      async getReturnSaleOrderrecordDetail(id) {
        const data = await getReturnSaleOrderrecordDetail(id);
        this.detailList;
        this.form.detailList = data.productList.map((item) => {
          item['reason'] = item.returnReason;
          item['weight'] = item.receiveTotalWeight;
          item['measurementCount'] = item.totalCount;
          item['measurementUnit'] = item.measuringUnit;
          return item;
        });
        this.detailList = JSON.parse(JSON.stringify(this.form.detailList));
      },
      //选择退货单
      handleOrderBtn() {
        this.returnOrderDialogFlag = true;
      },
      //退货单
      getReturnOrderInfo(row) {
        this.form.returnNo = row.returnNo;
        this.form.returnRecordId = row.id;
        this.form.sendNo = row.sendNo;
        this.form.orderNo = row.orderNo;
        this.form.orderId = row.orderId;
        this.form.orderIds = row.orderIds;
        this.getReturnSaleOrderrecordDetail(row.id);
      },
      //选择退货明细
      handleSelectGoods() {},
      //选择退货信息回调
      saveDate(data) {},

      cancel() {
        this.$emit('update:addOrEditDialogFlag', false);
      },
      async handleSubmit(type) {
        await this.$refs.formRef.validate(async (validate, obj) => {
          if (obj) {
            let messages = Object.keys(obj).map((key) => obj[key][0]);
            if (messages.length > 0) {
              this.$message.warning(messages[0].message);
            }
          }
          if (!validate) return;
          let params = {
            detailList: this.form.detailList.map((i) => {
              i['orderNo`'] = i.orderNo || this.form.orderNo;
              i['returnRecordId`'] =
                i.returnRecordId || this.form.returnRecordId;
              i['sendNo`'] = i.sendNo || this.form.sendNo;
              i['orderId`'] = i.orderId || this.form.orderId;

              return i;
            }),
            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})
            await this.submit(data);
            return;
          }
          this.$emit('done');
          this.cancel();
        });
      },
      async submit(res) {
        const data = await saleReturnGetByIdAPI(this.form.id || res);
        this.processSubmitDialogFlag = true;

        this.$nextTick(() => {
          let params = {
            businessId: this.form.id || res,
            businessKey: 'sales_return_handle_approve_new',
            formCreateUserId: data.createUserId,
            variables: {
              businessCode: data.returnHandleNo,
              businessName: data.contactName,
              businessType: '售后退货处理单'
            }
          };

          this.$refs.processSubmitDialogRef.init(params);
        });
      },
      reload() {
        this.cancel();
        this.$emit('done');
      }
    }
  };
</script>
<style scoped lang="scss">
  :deep .el-form-item {
    margin-bottom: 0;
  }
</style>
