<template>
  <div class="ele-body">
    <el-card shadow="never" class="tabs_box">
      <div class="page-title">
        <PageHeader title="详情"> </PageHeader>
      </div>
      <headerTitle style="margin-top: 10px" />
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-position="right"
        label-width="140px"
      >
        <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="计划数量：">
              <el-input v-model="form.order" disabled></el-input>
            </el-form-item>
          </el-col> -->

          <!-- <el-col :lg="8" :md="12" :sm="12" :xl="8" :xs="12">
            <el-form-item label="BOM类型：">
              <el-input v-model="form.order" disabled></el-input>
            </el-form-item>
          </el-col> -->

          <!-- <el-col :lg="8" :md="12" :sm="12" :xl="8" :xs="12">
            <el-form-item label="BOM版本：">
              <el-input v-model="form.order" 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.order" 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.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.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-row>
      </el-form>

      <seek-page :seekList="seekList" @search="search"></seek-page>

      <div class="btn_box">
        <el-button type="success" size="mini" @click="borrowOrder">
          领用申请
        </el-button>

        <el-button type="warning" size="mini" @click="pickOrder(2)">
          领料申请
        </el-button>

        <el-button type="primary" size="mini" @click="pickOrder(1)">
          下料申请
        </el-button>

        <!-- <el-button type="danger" size="mini" @click="materialReturn">
          退料申请
        </el-button> -->
      </div>

      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        :selection.sync="selection"
        row-key="id"
        cache-key="entrust_list_data_2026_11"
        :height="tableHeight"
        :pageSize="20"
        @fullscreen-change="fullscreenChange"
        @refresh="refreshList"
      >
        <template #quantity="{ row }">
          <span
            >{{ row.feedingControlQty ? row.feedingControlQty : 0 }}/{{
              row.quantity ? row.quantity : 0
            }}</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 #produceType="{ row }">
          <el-tag type="warning" size="small" v-if="row.produceType">{{
            produceTypeMap[row.produceType] || ''
          }}</el-tag>
          <span v-else></span>
        </template>
      </ele-pro-table>
    </el-card>

    <order-list ref="orderListRef" @refresh="refreshList" />
    <borrow-list ref="borrowListRef" />
    <picking-list ref="pickingListRef" />
  </div>
</template>

<script>
  import {
    getRequirementListPlanDetail,
    getRequirementListPlanDetailPage
  } from '@/api/requirementListPlan';

  import orderList from './components/orderList.vue';
  import borrowList from './components/borrowList.vue';
  import pickingList from './components/pickingList.vue';
  import PageHeader from '@/components/PageHeader';

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

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

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

  export default {
    components: { orderList, borrowList, pickingList, PageHeader },

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

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

        componentAttributeMap: COMPONENT_ATTRIBUTE_MAP,
        attributeTypeMap: ATTRIBUTE_TYPE_MAP,
        produceTypeMap: PRODUCE_TYPE_MAP
      };
    },

    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'
          },
          {
            label: '批次号',
            prop: 'batchNo',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'categoryLevelName',
            label: '物料分类',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'componentAttribute',
            label: '属性类型',
            width: 100,
            align: 'center',
            showOverflowTooltip: true,
            slot: 'componentAttribute'
          },
          {
            prop: 'attributeType',
            label: '存货类型',
            width: 100,
            align: 'center',
            showOverflowTooltip: true,
            slot: 'attributeType'
          },
          {
            prop: 'produceType',
            label: '生产类型',
            width: 100,
            align: 'center',
            showOverflowTooltip: true,
            slot: 'produceType'
          },
          {
            prop: 'categoryCode',
            label: '物料编码',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'type',
            label: '需求订单号',
            width: 100,
            align: 'center',
            showOverflowTooltip: true,
            slot: 'type'
          },
          {
            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: 'baseQuantity',
            label: '基本数量',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'quantity',
            label: '投料控制数量/定额数量',
            width: 190,
            align: 'center',
            showOverflowTooltip: true,
            slot: 'quantity'
          },
          {
            prop: 'measuringUnit',
            label: '计量单位',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'brandNum',
            label: '牌号',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'weight',
            label: '重量',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'weightUnit',
            label: '重量单位',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'pickQuantity',
            label: '申领数量',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'unPickQuantity',
            label: '未领数量',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'outQuantity',
            label: '已出库数量',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'unOutQuantity',
            label: '未出库数量',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'feedQuantity',
            label: '已投数量',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'unFeedQuantity',
            label: '未投数量',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'oddmentsQuantity',
            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
          }
        ];
      },
      seekList() {
        return [
          {
            label: '编码:',
            value: 'categoryCode',
            type: 'input',
            labelWidth: 50
          }
        ];
      }
    },

    mounted() {
      this.initPage();
    },

    methods: {
      initPage() {
        const { id, type } = this.$route.query;
        if (!id || type !== 'plan') return;

        this.id = id;
        this.loadDetail(id);
        // this.loadDetailPage(id);
      },

      async loadDetail(id) {
        this.form = (await getRequirementListPlanDetail(id)) || {};
      },

      async loadDetailPage(id) {
        const res = await getRequirementListPlanDetailPage({
          materialRequirementsId: id
        });
        this.detailList = res?.list || [];
        this.selection = [];
      },

      async datasource({ page, limit, where }) {
        const res = await getRequirementListPlanDetailPage({
          ...where,
          pageNum: page,
          size: limit,
          materialRequirementsId: this.$route.query.id
        });
        return res?.list || [];
      },

      async pickOrder(type) {
        if (!this.selection.length) {
          this.$message.warning('请选择一条数据');
          return;
        }

        // if (this.submitting) return;
        // this.submitting = true;

        // const isBorrow = type == 1;

        // const loading = this.$loading({
        //   lock: true,
        //   fullscreen: true,
        //   text: isBorrow ? '领用中...' : '领料中...'
        // });

        const detailList = this.selection.map((item) => ({
          ...item,
          quantity: item.unPickQuantity,
          id: undefined
        }));

        const params = {
          ...this.form,
          detailList,
          materialRequirements: this.form.code,
          type,
          remark: ''
        };

        this.$refs.orderListRef.open(params);

        // try {
        //   const api = isBorrow ? saveBorrowOrder : savePickingOrder;

        //   await api({
        //     ...this.form,
        //     detailList,
        //     materialRequirements: this.form.code
        //   });

        //   this.$message.success(isBorrow ? '领用成功' : '领料成功');

        //   this.selection = [];
        //   this.loadDetailPage(this.id);
        // } catch (e) {
        //   this.$message.error('操作失败，请稍后重试');
        // } finally {
        //   loading.close();
        //   this.submitting = false;
        // }
      },

      borrowOrder() {
        this.$refs.borrowListRef.open(this.form);
      },

      materialReturn() {
        if (!this.selection.length) {
          this.$message.warning('请选择一条数据');
          return;
        }

        for (let item of this.selection) {
          if (item.oddmentsQuantity <= 0) {
            this.$message.warning('所选物料存在有余料为0的情况，请重新选择');
            return;
          }
        }

        const detailList = this.selection.map((item) => ({
          ...item,
          quantity: item.oddmentsQuantity,
          id: undefined
        }));

        const params = {
          ...this.form,
          detailList,
          materialRequirements: this.form.code,
          type: 3,
          remark: ''
        };

        this.$refs.orderListRef.open(params);
      },

      refreshList() {
        // this.loadDetailPage(this.id);
        this.reload();
      },

      reload(where) {
        this.$refs.table.reload({ page: 1, where: where });
      },

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

      search(where) {
        this.reload(where);
      },

      closeDetail() {
        this.$router.back();
      }
    }
  };
</script>

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

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