<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <seek-page :seekList="seekList" @search="search"></seek-page>
      <!-- <order-search @search="reload" ref="searchRef"> </order-search> -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        :selection.sync="selection"
        row-key="id"
        cache-key="entrust_list_data"
        :height="tableHeight"
        :pageSize="20"
        @fullscreen-change="fullscreenChange"
      >
        <template v-slot:type="{ row }">
          <span> {{ getDictValue('请托类型', row.type + '') }}</span>
        </template>

        <template v-slot:totalCount="{ row }">
          <span> {{ row.totalCount }}{{ row.measuringUnit }}</span>
        </template>

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

        <template v-slot:sendStatus="{ row }">
          <el-tag v-if="row.sendStatus == 0 || !row.sendStatus">{{
            '未发货'
          }}</el-tag>
          <el-tag v-else-if="row.sendStatus == 1" type="success">{{
            '已发货'
          }}</el-tag>
          <el-tag v-else-if="row.sendStatus == 2" type="success">{{
            '已收货'
          }}</el-tag>
          <el-tag v-else-if="row.sendStatus == 3" type="success">{{
            '受托已发'
          }}</el-tag>
          <el-tag v-else-if="row.sendStatus == 4" type="success">{{
            '请托已收'
          }}</el-tag>
          <el-tag v-else-if="row.sendStatus == 5" type="success">{{
            '受托拒收'
          }}</el-tag>
          <el-tag v-else-if="row.sendStatus == 6" type="success">{{
            '请托拒收'
          }}</el-tag>
          <el-tag v-else-if="row.sendStatus == 7" type="success">{{
            '部分发货'
          }}</el-tag>
          <el-tag v-else-if="row.sendStatus == 8" type="success">{{
            '部分收货'
          }}</el-tag>
          <el-tag v-else-if="row.sendStatus == 9" type="success">{{
            '部分驳回'
          }}</el-tag>
        </template>

        <template v-slot:approvalStatus="{ row }">
          <el-tag v-if="row.approvalStatus == 0">未提交</el-tag>
          <el-tag v-if="row.approvalStatus == 1" type="warning">审核中</el-tag>
          <el-tag v-if="row.approvalStatus == 2" type="success"
            >审核通过</el-tag
          >
          <el-tag v-if="row.approvalStatus == 3" type="danger"
            >审核不通过</el-tag
          >
        </template>

        <template v-slot:code="{ row }">
          <el-link
            type="primary"
            :underline="false"
            @click="open('detail', row)"
          >
            {{ row.code }}
          </el-link>
        </template>
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="open('add')"
          >
            新建
          </el-button>

          <el-button
            size="small"
            type="success"
            icon="el-icon-printer"
            class="ele-btn-icon"
            @click="print"
          >
            打印
          </el-button>
        </template>

        <template v-slot:action="{ row }">
          <el-link
            type="primary"
            v-if="
              (row.status == 0 &&
                row.approvalStatus != 1 &&
                row.approvalStatus != 2) ||
              row.approvalStatus == 3
            "
            :underline="false"
            @click="open('edit', row)"
          >
            编辑
          </el-link>
          <el-popconfirm
            class="ele-action"
            v-if="
              (row.status == 0 &&
                row.approvalStatus != 1 &&
                row.approvalStatus != 2) ||
              row.approvalStatus == 3
            "
            title="确定要删除吗？"
            @confirm="remove([row.id])"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false"> 删除 </el-link>
            </template>
          </el-popconfirm>

          <el-link
            type="primary"
            :underline="false"
            @click="submit(row)"
            v-if="row.approvalStatus != 1 && row.approvalStatus != 2"
          >
            提交
          </el-link>

          <el-link
            type="primary"
            :underline="false"
            @click="sendGoods(row, 'add')"
            v-if="
              row.approvalStatus == 2 &&
              (row.sendStatus == 0 || !row.sendStatus || row.sendStatus == 5 || row.sendStatus == 7 || row.sendStatus == 9)
            "
          >
            发货
          </el-link>

          <el-link
            type="primary"
            :underline="false"
            @click="sendGoods(row, 'receipt')"
            v-if="row.approvalStatus == 2 && row.sendStatus == 3"
          >
            收货
          </el-link>

          <el-link
            type="primary"
            :underline="false"
            @click="sendGoods(row, 'receipt')"
            v-if="row.approvalStatus == 2 && row.sendStatus == 4"
          >
            收货详情
          </el-link>

          <el-link
            type="primary"
            :underline="false"
            @click="sendGoods(row, 'detail')"
            v-if="
              row.approvalStatus == 2 &&
              row.sendStatus != 0 &&
              row.sendStatus &&
              row.sendStatus != 5
            "
          >
            发货详情
          </el-link>

          <el-link
            type="primary"
            :underline="false"
            @click="handleFlow(row)"
            v-if="row.approvalStatus != 0"
          >
            流程
          </el-link>
        </template>
      </ele-pro-table>
    </el-card>
    <Create ref="create" @refresh="reload" />
    <ele-modal
      :visible.sync="visible"
      v-if="visible"
      width="20vw"
      append-to-body
      :maxable="true"
    >
      <el-form label-width="100px">
        <el-form-item label="入库仓库:" prop="warehouseId">
          <el-select v-model="warehouseId">
            <el-option
              v-for="item in warehouseList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="warehouseEntry"> 确定 </el-button>
      </template>
    </ele-modal>

    <flow ref="flowRef"></flow>
    <pleasePrint ref="pleasePrintRef"></pleasePrint>
    <goodsDetail ref="goodsDetailRef" @done="refresh"></goodsDetail>

    <process-submit-dialog
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="reload"
      :isNotNeedProcess="false"
    ></process-submit-dialog>
  </div>
</template>

<script>
  import OrderSearch from './components/order-search.vue';
  import dictMixins from '@/mixins/dictMixins';
  import Create from './components/create';
  import flow from '@/views/materialReturn/components/flow.vue';
  import pleasePrint from './components/pleasePrint.vue';
  import warehouseDefinition from '@/api/warehouseManagement/warehouseDefinition';
  import goodsDetail from './components/goodsDetail.vue';
  import { getByCode } from '@/api/system/dictionary-data';
  import { mapGetters } from 'vuex';
  import processSubmitDialog from '@/components/processSubmitDialog/processSubmitDialog.vue';
  import {
    getWarehouseList

    // queryKilnXCH
  } from '@/api/mes';
  import {
    getList,
    remove,
    submit,
    warehouseEntry
  } from '@/api/entrust/index.js';

  export default {
    components: {
      OrderSearch,
      Create,
      flow,
      pleasePrint,
      goodsDetail,
      processSubmitDialog
    },
    mixins: [dictMixins],
    data() {
      return {
        visible: false,
        loading: false,
        id: '',
        warehouseId: '',
        selection: [],
        warehouseList: [],
        tableHeight: 'calc(100vh - 320px)',
        factoryList: [],
        typeList: [],
        processSubmitDialogFlag: false
      };
    },
    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: 'type',
            label: '类型',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            slot: 'type'
          },
          {
            prop: 'priority',
            label: '紧急程度',
            width: 90,
            align: 'center',
            showOverflowTooltip: true,
            formatter: (row, column, cellValue) => {
              return cellValue == 1 ? '一般' : cellValue == 2 ? '紧急' : '';
            }
          },
          {
            prop: 'name',
            label: '名称',
            width: 130,
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            prop: 'code',
            slot: 'code',
            label: '编码',
            width: 160,
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            prop: 'applyFactoriesName',
            label: '所属工厂',
            align: 'center',
            width: 130,
            showOverflowTooltip: true
          },
          {
            prop: 'applyDeptName',
            label: '请托部门',
            align: 'center',
            width: 120,
            showOverflowTooltip: true
          },
          {
            prop: 'createUserName',
            label: '请托人',
            align: 'center',
            width: 80,
            showOverflowTooltip: true
          },
          {
            prop: 'totalCount',
            slot: 'totalCount',
            label: '请托数量',
            align: 'center',
            width: 130,
            showOverflowTooltip: true
          },
          {
            prop: 'beEntrustedFactoriesName',
            label: '受托工厂',
            align: 'center',
            width: 130,
            showOverflowTooltip: true
          },
          {
            prop: 'beEntrustedDeptName',
            label: '受托部门',
            align: 'center',
            width: 120,
            showOverflowTooltip: true
          },
          {
            prop: 'productionPlanCode',
            label: '计划编号',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'produceRoutingName',
            label: '工艺路线',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'bomType',
            label: 'BOM分类',
            align: 'center',
            width: 100,
            showOverflowTooltip: true,
            formatter: (row) => {
              if (row.bomType == 1) {
                return '产品(PBOM)';
              }
              if (row.bomType == 2) {
                return '加工(MBOM)';
              }
              if (row.bomType == 3) {
                return '装配(ABOM)';
              }
              return '';
            }
          },
          {
            prop: 'bomCategoryVersions',
            label: 'BOM版本',
            align: 'center',
            width: 100,
            showOverflowTooltip: true,
            formatter: (row) => {
              if (row.bomCategoryName) {
                return `${row.bomCategoryName} (V${row.bomCategoryVersions}.0)`;
              }
              return '';
            }
          },
          {
            prop: 'brandNum',
            label: '牌号',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'batchNo',
            label: '批次号',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'planStartTime',
            label: '计划开始时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 130,
            sortable: true
          },
          {
            prop: 'planCompleteTime',
            label: '计划结束时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 130,
            sortable: true
          },
          {
            prop: 'specification',
            label: '规格',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'modelType',
            label: '型号',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'sendStatus',
            slot: 'sendStatus',
            label: '发货状态',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'workOrderCode',
            label: '生产工单号',
            slot: 'workOrderCode',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'planDeliveryTime',
            label: '完成时间',
            align: 'center',
            width: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'createTime',
            label: '创建时间',
            align: 'center',
            width: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'describes',
            label: '需求描述',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'status',
            label: '状态',
            align: 'center',
            slot: 'status',
            width: 100
          },

          {
            prop: 'approvalStatus',
            label: '审批状态',
            align: 'center',
            slot: 'approvalStatus',
            width: 120
          },

          {
            prop: 'beReason',
            label: '原因',
            align: 'center',
            slot: 'beReason',
            width: 150
          },

          {
            columnKey: 'action',
            label: '操作',
            width: 220,
            align: 'center',
            resizable: false,
            fixed: 'right',
            slot: 'action',
            showOverflowTooltip: true
          }
        ];
      },

      seekList() {
        return [
          {
            label: '类型:',
            value: 'type',
            type: 'select',
            labelWidth: 50,
            planList: this.typeList
          },
          {
            label: '名称:',
            value: 'name',
            type: 'input',
            labelWidth: 50
          },
          {
            label: '受托工厂:',
            value: 'beEntrustedFactoriesId',
            type: 'select',
            planList: this.factoryList
          },
          {
            label: '完成时间:',
            value: 'planDeliveryTime',
            type: 'date',
            dateType: 'daterange',
            placeholder: ''
          }
        ];
      },
      ...mapGetters(['user'])
    },
    created() {
      this.getTypeList('entrust_type');
      this.requestDict('请托类型');
      getWarehouseList().then((res) => {
        this.warehouseList = res;
      });
      this.getFactoryList();
    },
    filters: {},
    methods: {
      /* 表格数据源 */
      datasource({ page, limit, where }) {
        return getList({
          pageNum: page,
          size: limit,
          ...where
        });
      },
      open(type, row) {
        this.$refs.create.open(type, row);
      },

      async getTypeList(code) {
        getByCode(code).then((res) => {
          let _arr = [];
          res.data.map((item) => {
            const key = Object.keys(item)[0];
            const value = item[key];
            _arr.push({ label: value, value: key });
          });

          this.typeList = _arr;
        });
      },

      async getFactoryList() {
        const { list } = await warehouseDefinition.getFactoryarea({
          pageNum: 1,
          size: 999,
          type: 1
        });

        list.forEach((item) => {
          item.label = item.name;
          item.value = item.id;
        });

        this.factoryList = list || [];
      },

      refresh() {
        this.reload();
      },

      openWarehouseEntry(id) {
        this.id = id;
        this.visible = true;
      },
      warehouseEntry() {
        if (!this.warehouseId) {
          this.$message.error('请选择仓库');
          return;
        }
        warehouseEntry({
          id: this.id,
          warehouseId: this.warehouseId
        }).then((res) => {
          this.reload();
          this.visible = false;
        });
      },
      remove(id) {
        let ids = id || this.selection.map((item) => item.id);
        remove(ids).then((res) => {
          this.$message.success('删除' + res);
          this.reload();
        });
      },

      submit(item) {
        let businessType = '请托受托审批';
        this.processSubmitDialogFlag = true;
        // this.$confirm('是否提交该请托单的审核流程?', '提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // })
        //   .then(() => {
        //     submit({
        //       businessId: item.id,
        //       beEntrustedDeptId: item.beEntrustedDeptId
        //     }).then((res) => {
        //       this.$message.success('提交' + res.message);
        //       this.reload();
        //       this.visible = false;
        //     });
        //   })
        //   .catch(() => {});
        this.$nextTick(() => {
          let params = {
            businessId: item.id,
            businessKey: 'please_entrust_approve',
            formCreateUserId: this.user.info.userId,
            variables: {
              businessCode: item.code,
              businessName: '请托受托审批',
              businessType: businessType,
              beEntrustedDeptId: item.beEntrustedDeptId
            }
          };
          this.$refs.processSubmitDialogRef.init(params);
        });
      },
      /* 刷新表格 */
      reload(where) {
        this.$nextTick(() => {
          this.$refs.table.reload({ page: 1, where });
        });
      },

      sendGoods(item, type) {
        this.$refs.goodsDetailRef.open(item, type);
      },

      fullscreenChange(fullscreen) {
        if (fullscreen) {
          this.tableHeight = 'calc(100vh - 120px)';
        } else {
          this.tableHeight = 'calc(100vh - 320px)';
        }
      },

      handleFlow(row) {
        if (!row.processInstanceId) {
          return this.$message.warning('暂无流程图');
        }
        this.$refs.flowRef.open(row.processInstanceId);
      },

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

      print() {
        if (this.selection.length == 0) {
          return this.$message.warning('请选择一条打印的数据');
        }

        if (this.selection.length > 1) {
          return this.$message.warning('只能选择一条打印的数据');
        }

        this.$refs.pleasePrintRef.open(this.selection);
      }
    }
  };
</script>

<style lang="scss" scoped></style>
