<template>
  <div>
    <el-dialog :title="`选择${type == 1 ? '入库' : '出库'}申请单`" :visible.sync="dialogVisible" width="90%"
      :before-close="handleClose" :close-on-click-modal="false" :close-on-press-escape="false">
      <div v-if="bizType == 10">
        <ele-pro-table ref="table" :columns="columns10" :datasource="datasource10" cache-key="workOrderTable"
          @cell-click="cellClick10">
          <template v-slot:selection="{ row }">
            <el-radio class="radio" v-model="currentRow.id" :label="row.id"><i></i></el-radio>
          </template>
          <template v-slot:requireDeliveryTime="{ row }">
            <span v-if="row.deliveryMethod == 1">{{
              row.requireDeliveryTime
            }}</span>

            <el-link v-if="row.deliveryMethod == 2" type="primary" :underline="false"
              @click.native="handleMethod(row)">分批时间</el-link>
          </template>

          <template v-slot:type="{ row }">
            <div v-if="row.type == 1">采购委外</div>
            <div v-if="row.type == 2">直接发货委外</div>
            <div v-if="row.type == 3">无采购委外</div>
          </template>

          <template v-slot:status="{ row }">
            <el-tag>{{ row.status == 1 ? '已发布' : '未发布' }}</el-tag>
          </template>

          <template v-slot:technicalDrawings="{ row }">
            <div v-if="row.technicalDrawings && row.technicalDrawings?.length">
              <el-link v-for="link in row.technicalDrawings" :key="link.id" type="primary" :underline="false"
                @click="downloadFile(link)">
                {{ link.name }}</el-link>
            </div>
          </template>

          <template v-slot:files="{ row }">
            <div v-if="row.files && row.files?.length">
              <el-link v-for="link in row.files" :key="link.id" type="primary" :underline="false"
                @click="downloadFile(link)">
                {{ link.name }}</el-link>
            </div>
          </template>
        </ele-pro-table>
      </div>
      <div class="main" v-if="bizType != 10">
        <!-- @cell-click="cellClick" -->
        <ele-pro-table ref="table" :columns="columns" :datasource="datasource" @select="selectChange"
          @select-all="changeSelectAll" cache-key="workOrderTable">
          <!-- 表头工具栏 -->
          <!-- <template v-slot:action="{ row }">
            <el-radio class="radio" v-model="currentId" :label="row.id"
              ><i></i
            ></el-radio>
          </template> -->
          <template v-slot:totalCount="{ row }">
            {{ row.totalCount }} {{ row.measuringUnit }}
          </template>

          <template v-slot:totalPackage="{ row }">
            {{ row.totalPackage }}
          </template>

          <template v-slot:totalWeight="{ row }">
            {{ row.totalWeight }} {{ row.weightUnit }}
          </template>

          <template v-slot:status="{ row }">
            <span>
              {{ statusFormatter(row.status) }}
            </span>
          </template>
        </ele-pro-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleMine()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { outputSceneState, sceneState } from '@/utils/dict/index';
import storageApi from '@/api/warehouseManagement';
import { getCode } from '@/api/codeManagement/index.js';
export default {
  props: {
    // 1入库 2出库
    type: {
      type: String,
      default: '1'
    },
    bizType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      outputSceneState,
      sceneState,
      dialogVisible: false,
      currentRow: {},
      checkRadioData: [],
      currentId: '',
      statusOpt: [
        { label: '待处理', value: 0 },
        { label: '已处理', value: 1 },
        { label: '已撤销', value: 2 }
      ],
      currentRow10: {}
    };
  },
  computed: {
    // 表格列配置
    columns() {
      return [
        // {
        //   action: 'action',
        //   slot: 'action',
        //   align: 'center',
        //   label: '选择'
        // },
        {
          width: 45,
          type: 'selection',
          columnKey: 'selection',
          align: 'center'
        },
        {
          columnKey: 'index',
          label: '序号',
          type: 'index',
          width: 55,
          align: 'center',
          showOverflowTooltip: true,
          fixed: 'left'
        },
        {
          prop: 'code',
          label: '编码',
          align: 'center',
          minWidth: 100
        },
        {
          prop: 'categoryNames',
          label: '名称',
          showOverflowTooltip: true,
          align: 'center'
        },
        { label: '型号', prop: 'modelType', width: '150' },
        { label: '规格', prop: 'specification', width: '150' },
        { label: '牌号', prop: 'brandNum', width: '100' },
        {
          prop: 'sourceType',
          label: '出入库类型',
          align: 'center',
          formatter: (row, column, cellValue) => {
            switch (this.type) {
              case '1':
                // 入库
                return this.sceneState.filter(
                  (item) => item.code == row.sourceType
                )[0].label;
              case '2':
                // 出库
                return this.outputSceneState.filter(
                  (item) => item.code == row.sourceType
                )[0].label;
            }
          }
        },
        {
          prop: 'approvalUserName',
          label: '审核人',
          align: 'center'
        },
        {
          prop: 'createUserName',
          label: '申请人',
          align: 'center'
        },
        {
          prop: 'createTime',
          label: '创建时间',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 110
        },
        {
          slot: 'status',
          label: '状态',
          align: 'center'
        }
      ];
    },
    columns10() {
      return [
        {
          slot: 'selection',
          label: '选择',
          width: 50,
          align: 'center'
        },
        {
          columnKey: 'index',
          label: '序号',
          type: 'index',
          width: 55,
          align: 'center',
          showOverflowTooltip: true,
          fixed: 'left'
        },

        {
          prop: 'code',
          label: '委外单编码',
          align: 'center'
        },
        {
          prop: 'name',
          label: '委外单名称',
          align: 'center'
        },

        {
          prop: 'workOrderCode',
          label: '工单编码',
          align: 'center'
        },

        {
          prop: 'taskName',
          label: '工序',
          align: 'center'
        },

        {
          prop: 'totalCount',
          label: '委外数量',
          align: 'center'
        },

        {
          prop: 'totalWeight',
          label: '委外重量',
          align: 'center'
        },

        {
          slot: 'type',
          label: '委外类型',
          align: 'center'
        },

        {
          prop: 'remark',
          label: '备注',
          align: 'center'
        },

        {
          slot: 'requireDeliveryTime',
          label: '预计到货日期',
          align: 'center',
          minWidth: 70
        },

        {
          prop: 'produceRoutingName',
          label: '工艺路线',
          align: 'center'
        },

        {
          prop: 'warehouseName',
          label: '仓库',
          align: 'center'
        },

        {
          prop: 'createTime',
          label: '创建时间',
          align: 'center',
          minWidth: 70
        },

        {
          slot: 'status',
          label: '状态',
          align: 'center'
        },

        {
          label: '图片附件',
          slot: 'technicalDrawings',
          action: 'technicalDrawings',
          minWidth: 100
        },

        {
          label: '附件',
          slot: 'files',
          action: 'files',
          minWidth: 100
        }
      ];
    }
  },
  created() {
    console.log(this.type, 'this.typethis.typethis.typethis.type')
  },
  methods: {
    /* 表格数据源 */
    datasource({ page, limit, where }) {
      return storageApi.getinboundRequestsList({
        pageNum: page,
        size: limit,
        status: 0,
        type: this.type,
        ...where
      });
    },
    /* 表格数据源 委外入库 */
    datasource10({ page, limit, where }) {
      return storageApi.getApplyoutsource({
        pageNum: page,
        size: limit,
        ...where
      });
    },
    cellClick10(row) {
      this.currentRow10 = row;
    },
    downloadFile(file) {
      getFile({ objectName: file.storePath }, file.name);
    },

    handleFlow(row) {
      this.$refs.flowRef.open(row.processInstanceId);
    },

    handleDetails(row) {
      this.$refs.detailsRef.open(row);
    },

    handleMethod(row) {
      this.$refs.timeDialogRef.open(row, 'details');
    },

    handleRelease(row) {
      this.$refs.releaseRef.open(row);
    },
    // 全选
    changeSelectAll(arr) {
      console.log('changeSelectAll---------', arr);
      let isBoolean = arr.every(
        (item) => arr[0].sourceType == item.sourceType
      );
      if (!isBoolean) {
        this.checkRadioData = [];
        this.$refs.table.clearSelection();
        return this.$message.error(
          `所选${this.type == 1 ? '入库' : '出库'
          }申请单出入库类型不一致，请重新选择`
        );
      }
      if (arr.length != 0) {
        this.checkRadioData = arr;
      } else {
        this.checkRadioData = [];
      }
    },
    selectChange(arr, row) {
      console.log('selectChange---------', arr);
      let isBoolean = arr.every(
        (item) => arr[0].sourceType == item.sourceType
      );
      if (!isBoolean) {
        this.checkRadioData = [];
        this.$refs.table.clearSelection();
        return this.$message.error(
          `所选${this.type == 1 ? '入库' : '出库'
          }申请单出入库类型不一致，请重新选择`
        );
      }
      if (arr.length != 0) {
        this.checkRadioData = arr;
      } else {
        this.checkRadioData = [];
      }
    },
    handleMine(val) {
      console.log(val, 'valvalvalvalvalvalvalvalvalvalvalvalvalval确认按钮');
      console.log(this.bizType, 'this.bizType');
      if (this.bizType != 10) {
        let checkRadioData = val ? val : this.checkRadioData;
        if (checkRadioData.length < 1) {
          return this.$message.error(
            `请选择${this.type == 1 ? '入库' : '出库'}申请单`
          );
        }
        let isBoolean = checkRadioData.every(
          (item) => checkRadioData[0].sourceType == item.sourceType
        );
        if (!isBoolean) {
          return this.$message.error(
            `所选${this.type == 1 ? '入库' : '出库'
            }申请单出入库类型不一致，请重新选择`
          );
        }
        let aaa = checkRadioData.map((item) => item.id);
        storageApi.getApplystoragedetails(aaa).then(async (res) => {
          if (this.type == 2) {
            // 出库
            let data = await storageApi.getHierarchyFifo({
              type: 1,
              builders: res.map((item) => {
                return {
                  categoryId: item.categoryId,
                  num: item.measureQuantity
                };
              })
            });
            if (data?.length > 0) {
              this.$emit('detailData', data, 1, {
                sourceBizNo: checkRadioData
                  .map((item) => item.code)
                  .join(','),
                bizType: checkRadioData[0].sourceType,
                assetType: Array.from(
                  new Set(res.map((item) => item.rootCategoryLevelId))
                ).join(',')
              });
              this.dialogVisible = false;
            } else {
              this.$message.warning('该出库申请单无库存');
            }
          } else {
            // 入库
            const batchNo = await getCode('lot_number_code');
            let data = res.map((item, index) => {
              return {
                ...item,
                index,
                packingQuantity: 1,
                minPackingQuantity: item.measureQuantity,
                measureUnit: item.measuringUnit,
                batchNo,
                id: '',
                warehouseIds: [item.warehouseId],
                warehouseNames: [item.warehouseName]
              };
            });

            this.$emit('detailData', data, 1, {
              sourceBizNo: checkRadioData.map((item) => item.code).join(','),
              bizType: checkRadioData[0].sourceType,
              assetType: Array.from(
                new Set(res.map((item) => item.rootCategoryLevelId))
              ).join(',')
            });
            this.dialogVisible = false;
          }
        });
      } else {
        console.log(this.currentRow10, '10');
        this.$emit('detailData', [], 1, {
          sourceBizNo: this.currentRow10.code,
          taskId: this.currentRow10.taskId,
          workOrderId: this.currentRow10.workOrderId
        });
        this.dialogVisible = false;
      }
    },
    // 单击获取id
    cellClick(row) {
      this.currentRow = row;
      this.currentId = row.id;
    },
    statusFormatter(status) {
      const obj = this.statusOpt.find((i) => i.value == status);
      return obj && obj.label;
    },
    open() {
      this.dialogVisible = true;
    },
    handleClose() {
      this.dialogVisible = false;
    }
  }
};
</script>
