<template>
  <ele-modal
    width="80vw"
    :visible.sync="visible"
    custom-class="ele-dialog-form"
    :before-close="cancel"
    :title="title"
    :maxable="true"
    append-to-body
  >
    <div class="switch" style="margin-bottom: 10px">
      <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
      ref="form"
      :model="form"
      :rules="rules"
      label-position="right"
      label-width="140px"
      v-if="activeComp == 'main'"
    >
      <el-row :gutter="10" class="basic">
        <el-col :lg="8" :md="12" :sm="12" :xl="8" :xs="12">
          <el-form-item label="计划编号：">
            <el-input v-model="form.planCode" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="8" :md="12" :sm="12" :xl="8" :xs="12">
          <el-form-item label="批次号：">
            <el-input v-model="form.batchNo" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="8" :md="12" :sm="12" :xl="8" :xs="12">
          <el-form-item label="编码：">
            <el-input v-model="form.categoryCode" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="8" :md="12" :sm="12" :xl="8" :xs="12">
          <el-form-item label="名称：">
            <el-input v-model="form.categoryName" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="8" :md="12" :sm="12" :xl="8" :xs="12">
          <el-form-item label="零部件图号：">
            <el-input v-model="form.imgCode" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="8" :md="12" :sm="12" :xl="8" :xs="12">
          <el-form-item :label="orderCodeLabel">
            <el-input v-model="form.code" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="8" :md="12" :sm="12" :xl="8" :xs="12">
          <el-form-item label="需求订单号：">
            <el-input v-model="form.materialRequirements" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="8" :md="12" :sm="12" :xl="8" :xs="12">
          <el-form-item label="顶级产品编号：">
            <el-input v-model="form.topCategoryName" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="8" :md="12" :sm="12" :xl="8" :xs="12">
          <el-form-item label="顶级产品名称：">
            <el-input v-model="form.topCategoryName" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="24" :md="24" :sm="24" :xl="24" :xs="24">
          <el-form-item label="备注：">
            <el-input
              v-model="form.remark"
              type="textarea"
              :rows="2"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <ele-pro-table
      ref="table"
      :columns="columns"
      :datasource="form.detailList"
      :selection.sync="selection"
      row-key="id"
      cache-key="entrust_list_data"
      :height="tableHeight"
      :pageSize="20"
      @fullscreen-change="fullscreenChange"
      @refresh="refreshList"
      v-if="activeComp == 'main'"
    >
      <template v-slot:toolbar>
        <el-button
          type="primary"
          class="ele-btn-icon"
          size="small"
          @click="batchReturn"
          >批量退还</el-button
        >
      </template>

      <template #quantity="{ row }">
        <span>{{ row.quantity }}{{ row.measuringUnit }}</span>
      </template>

      <template #weight="{ row }">
        <span>{{ row.weight }}{{ row.weightUnit }}</span>
      </template>

      <template #componentAttribute="{ row }">
        <el-tag size="small" v-if="row.componentAttribute">{{
          componentAttributeMap[row.componentAttribute] || ''
        }}</el-tag>

        <span v-else></span>
      </template>

      <template #attributeType="{ row }">
        <el-tag type="success" size="small" v-if="row.attributeType">{{
          attributeTypeMap[row.attributeType] || ''
        }}</el-tag>
        <span v-else></span>
      </template>

      <template #borrowReturnStatus="{ row }">
        <el-tag size="small" v-if="row.borrowReturnStatus">{{
          returnStatusMap[row.borrowReturnStatus] || ''
        }}</el-tag>
        <span v-else></span>
      </template>

      <template #produceType="{ row }">
        <el-tag type="warning" size="small" v-if="row.produceType">{{
          produceTypeMap[row.produceType] || ''
        }}</el-tag>
        <span v-else></span>
      </template>

      <template #action="{ row }">
        <el-link
          :underline="false"
          type="primary"
          @click="singleOutDetailData(row)"
          >出库详情
        </el-link>
      </template>
    </ele-pro-table>

    <ele-pro-table
      ref="table"
      :columns="outColumns"
      :datasource="outList"
      :selection.sync="selection"
      row-key="id"
      cache-key="entrust_list_data"
      :height="tableHeight"
      :pageSize="20"
      @fullscreen-change="fullscreenChange"
      @refresh="refreshOutList"
      v-if="activeComp == 'out'"
    >
      <template #quantity="{ row }">
        <span>{{ row.quantity }}{{ row.measuringUnit }}</span>
      </template>

      <template #sourceType="{ row }">
        <el-tag size="small" v-if="row.sourceType">{{
          typeMap[row.sourceType]
        }}</el-tag>
        <span v-else></span>
      </template>

      <template #weight="{ row }">
        <span>{{ row.weight }}{{ row.weightUnit }}</span>
      </template>
    </ele-pro-table>

    <out-detail ref="outDetailRef" />
  </ele-modal>
</template>

<script>
  import {
    pickingOrderInfo,
    borrowOrderInfo,
    blankingOrderInfo,
    getOutOrderList,
    saveReturnOrder
  } from '@/api/requirementListPlan';

  import outDetail from './outDetail.vue';

  const COMPONENT_ATTRIBUTE_MAP = {
    1: '自制件',
    2: '采购件',
    3: '外协件',
    4: '受托件'
  };

  const ATTRIBUTE_TYPE_MAP = {
    1: '总装',
    2: '部装',
    3: '零件',
    4: '原材料'
  };

  const PRODUCE_TYPE_MAP = {
    1: '加工',
    2: '装配',
    3: '下料'
  };

  const TYPE_MAP = {
    1: '领料单',
    2: '领用单',
    3: '下料单'
  };

  const RETURN_STATUS_MAP = {
    1: '领用中',
    2: '已领用',
    3: '退还中',
    4: '已退还'
  };

  export default {
    components: { outDetail },

    data() {
      return {
        form: {},
        outList: [],
        rules: {},
        id: '',
        submitting: false,

        tableHeight: 'calc(100vh - 595px)',
        detailList: [],
        selection: [],
        visible: false,
        title: '',

        activeComp: 'main',
        tabOptions: [
          { key: 'main', name: '详情' },
          { key: 'out', name: '出库详情' }
        ],

        componentAttributeMap: COMPONENT_ATTRIBUTE_MAP,
        attributeTypeMap: ATTRIBUTE_TYPE_MAP,
        produceTypeMap: PRODUCE_TYPE_MAP,
        typeMap: TYPE_MAP,
        returnStatusMap: RETURN_STATUS_MAP,
        type: '',
        sourceCode: ''
      };
    },

    computed: {
      columns() {
        return [
          {
            columnKey: 'selection',
            type: 'selection',
            width: 45,
            align: 'center',
            fixed: 'left'
          },
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'categoryLevelName',
            label: '物料分类',
            width: 100,
            align: 'center',
            showOverflowTooltip: true,
            show: this.type == 2 ? false : true
          },
          {
            prop: 'componentAttribute',
            label: '属性类型',
            width: 100,
            align: 'center',
            showOverflowTooltip: true,
            slot: 'componentAttribute',
            show: this.type == 2 ? false : true
          },

          {
            prop: 'attributeType',
            label: '存货类型',
            width: 100,
            align: 'center',
            showOverflowTooltip: true,
            slot: 'attributeType',
            show: this.type == 2 ? false : true
          },

          {
            prop: 'produceType',
            label: '生产类型',
            width: 100,
            align: 'center',
            showOverflowTooltip: true,
            slot: 'produceType',
            show: this.type == 2 ? false : true
          },

          {
            prop: 'categoryCode',
            label: '物料编码',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },

          {
            prop: 'categoryName',
            label: '物料名称',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'modelType',
            label: '型号',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'specification',
            label: '规格',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'categorySize',
            label: '尺寸',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'brandNum',
            label: '牌号',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'borrowReturnStatus',
            slot: 'borrowReturnStatus',
            label: '状态',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'weight',
            slot: 'weight',
            label: '重量',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'quantity',
            slot: 'quantity',
            label: '领料数量',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'createTime',
            label: '创建时间',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 200,
            align: 'center',
            resizable: false,
            fixed: 'right',
            slot: 'action'
          }
        ];
      },
      seekList() {
        return [
          {
            label: '编码:',
            value: 'categoryCode',
            type: 'input',
            labelWidth: 50
          }
        ];
      },
      orderCodeLabel() {
        return this.type == 1
          ? '领料单号'
          : this.type == 3
          ? '领用单号'
          : this.type == 2
          ? '下料单号'
          : '退料单号';
      },
      outColumns() {
        return [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'batchNo',
            label: '批次号',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'brandNum',
            label: '牌号',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'categoryCode',
            label: '物品编码',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'categoryName',
            label: '物品名称',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'categoryLevelName',
            label: '物品分类名称',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'materialRequirements',
            label: '物料需求单号',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'specification',
            label: '规格',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'modelType',
            label: '型号',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'planCode',
            label: '生产计划单号',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'quantity',
            slot: 'quantity',
            label: '数量',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'weight',
            slot: 'weight',
            label: '重量',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'sourceCode',
            label: '来源编码',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'sourceType',
            slot: 'sourceType',
            label: '来源类型',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'substanceCode',
            label: '物品资产编码',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'supplierCode',
            label: '供应商编码',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'supplierName',
            label: '供应商名称',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'warehouseName',
            label: '来源仓库名称',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'createUserName',
            label: '创建人',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'createTime',
            label: '创建时间',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          }
        ];
      }
    },

    methods: {
      open(item, type) {
        this.visible = true;
        this.id = item.id;
        this.type = type;
        this.sourceCode = item.code;
        this.title =
          type == 1
            ? '领料单详情'
            : this.type == 3
            ? '领用单详情'
            : this.type == 2
            ? '下料单详情'
            : '退料单详情';
        this.loadDetailData(item.id);
        this.outDataDetailData(item.code);
      },

      async loadDetailData(id) {
        const URL =
          this.type == 1
            ? pickingOrderInfo
            : this.type == 2
            ? borrowOrderInfo
            : blankingOrderInfo;
        this.form = (await URL(id)) || {};
      },

      async outDataDetailData(sourceCode) {
        const res = await getOutOrderList({
          sourceCode
        });
        this.outList = res.list || [];
      },

      singleOutDetailData(item) {
        this.$refs.outDetailRef.open(item, this.sourceCode);
      },

      refreshList() {
        this.loadDetailData(this.id);
      },

      refreshOutList() {
        this.outDataDetailData(this.sourceCode);
      },

      async batchReturn() {
        if (!this.selection?.length) {
          return this.$message.warning('请先选择要退还的物料！');
        }
        if (this.type == 3) {
          const invalidItem = this.selection.find(
            (item) => item.borrowReturnStatus != 2
          );
          if (invalidItem) {
            return this.$message.warning('请选择已领用的物料进行退还！');
          }
        }

        try {
          await this.$confirm('是否确认批量退还所选物料？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          });

          const loading = this.$loading({
            lock: true,
            fullscreen: true,
            text: '退料中...'
          });

          try {
            const { detailList, executorTime, ...formData } = this.form;

            const detailListData = this.selection.map(
              ({ id, ...rest }) => rest
            );

            const params = {
              ...formData,
              detailList: detailListData,
              returnOrderType: this.type,
              sourceId: this.form.id,
              sourceCode: this.form.code
            };

            await saveReturnOrder(params);

            this.$message.success('退还成功');
            this.selection = [];
            this.loadDetailData(this.id);
          } finally {
            loading.close();
          }
        } catch (e) {}
      },

      cancel() {
        this.visible = false;
      },

      fullscreenChange(fullscreen) {
        this.tableHeight = fullscreen
          ? 'calc(100vh - 120px)'
          : 'calc(100vh - 595px)';
      }
    }
  };
</script>

<style scoped>
  ::v-deep .el-form-item {
    margin-bottom: 15px !important;
  }

  .btn_box {
    margin-bottom: 6px;
  }
</style>
