<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <!-- <order-search @search="reload" ref="searchRef"> </order-search> -->
      <seek-page :seekList="seekList" @search="search"></seek-page>

      <div class="btn_box">
        <!-- <el-button type="primary" @click="salesToProductionOpen(2)"
          >转生产订单</el-button
        > -->
        <el-button type="primary" @click="salesToProductionOpen(1)"
          >转生产计划</el-button
        >
      </div>

      <el-tabs v-model="tabValue" type="card" @tab-click="handleTabClick">
        <el-tab-pane label="受托任务" name="1"></el-tab-pane>
        <el-tab-pane label="预处理任务" name="2"></el-tab-pane>
      </el-tabs>
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        :current.sync="current"
        highlight-current-row
        row-key="id"
        cache-key="beEntrusted"
        :pageSize="20"
        :height="tableHeight"
        :selection.sync="selection"
        @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:receiveQuantity="{ row }">
          <span> {{ row.receiveQuantity || 0 }}{{ row.measuringUnit }}</span>
        </template>

        <template v-slot:changeType="{ row }">
          <el-tag v-if="row.changeType == 0 || !row.changeType">未转</el-tag>
          <el-tag v-else-if="row.changeType == 1" type="success"
            >已转生产订单</el-tag
          >
          <el-tag v-else-if="row.changeType == 2" type="success"
            >已转生产工单</el-tag
          >
          <el-tag v-else-if="row.changeType == 3" type="success"
            >已转生产计划</el-tag
          >
        </template>

        <template v-slot:status="{ row }">
          <el-tag v-if="row.status == 0 || !row.status">未提交</el-tag>
          <el-tag v-else-if="row.status == 1" type="success">已提交</el-tag>
          <el-tag v-else-if="row.status == 2" type="success">已发布</el-tag>
          <el-tag v-else-if="row.status == 4" type="success">待生产</el-tag>
          <el-tag v-else-if="row.status == 5" type="success">生产中</el-tag>
          <el-tag v-else-if="row.status == 6" type="success">已完成</el-tag>
          <el-tag v-else-if="row.status == 7" type="success">已延期</el-tag>
          <el-tag v-else-if="row.status == 8" type="success">待下达</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 == 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:action="{ row }">
          <el-link
            type="primary"
            :underline="false"
            @click="receiveGoos(row, 'add')"
            v-if="row.approvalStatus == 2 && (row.sendStatus == 1 || row.sendStatus == 8)"
          >
            收货
          </el-link>

          <el-link
            type="primary"
            :underline="false"
            @click="receiveGoos(row, 'send')"
            v-if="
              row.approvalStatus == 2 &&
              (row.sendStatus == 3 || row.sendStatus == 4)
            "
          >
            发货详情
          </el-link>

          <el-link
            type="primary"
            :underline="false"
            @click="receiveGoos(row, 'detail')"
            v-if="
              row.approvalStatus == 2 &&
              row.sendStatus != 1 &&
              row.sendStatus != 5
            "
          >
            收货详情
          </el-link>
        </template>
      </ele-pro-table>
    </el-card>
    <Create ref="create" @refresh="reload" />
    <ele-modal
      :visible.sync="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>

    <create-order ref="createOrderRef" @refresh="reload"></create-order>
    <goodsDetail ref="goodsDetailRef" @done="refresh"></goodsDetail>
  </div>
</template>

<script>
  import OrderSearch from '@/views/entrust/components/order-search.vue';
  import dictMixins from '@/mixins/dictMixins';
  import Create from '@/views/entrust/components/create';
  import createOrder from './components/create-order.vue';
  import {
    getList,
    warehouseEntry,
    update,
    transferProductionPlan
  } from '@/api/beEntrusted/index';
  import goodsDetail from './components/goodsDetail.vue';
  import warehouseDefinition from '@/api/warehouseManagement/warehouseDefinition';
  import { getByCode } from '@/api/system/dictionary-data';

  import {
    getWarehouseList

    // queryKilnXCH
  } from '@/api/mes';
  export default {
    components: {
      OrderSearch,
      Create,
      createOrder,
      goodsDetail
    },
    mixins: [dictMixins],
    data() {
      return {
        visible: false,
        loading: false,
        id: '',
        current: null,
        warehouseId: '',
        warehouseList: [],
        tableHeight: 'calc(100vh - 320px)',
        selection: [],
        factoryList: [],
        typeList: [],
        tabValue: '1'
      };
    },
    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: 'receiveQuantity',
            slot: 'receiveQuantity',
            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: 'sendStatus',
            slot: 'sendStatus',
            label: '收货状态',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'produceRoutingName',
            label: '工艺路线',
            align: 'center',
            showOverflowTooltip: true
          },

          {
            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: '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: 'changeType',
            label: '转换状态',
            align: 'center',
            slot: 'changeType',
            width: 120
          },
          {
            prop: 'beReason',
            label: '原因',
            align: 'center',
            slot: 'beReason',
            width: 150
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 180,
            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: 'applyFactoriesId',
            type: 'select',
            planList: this.factoryList
          },
          // {
          //   label: '状态:',
          //   value: 'preStatus',
          //   type: 'select',
          //   planList: [
          //     { value: 0, label: '准备中' },
          //     { value: 1, label: '准备完成' },
          //     { value: 2, label: '取消' }
          //   ]
          // },
          // {
          //   label: '受托工厂:',
          //   value: 'beEntrustedFactoriesId',
          //   type: 'select',
          //   planList: this.factoryList
          // },
          {
            label: '请托时间:',
            value: 'planDeliveryTime',
            type: 'date',
            dateType: 'daterange',
            placeholder: ''
          }
        ];
      }
    },
    created() {
      this.requestDict('请托类型');
      this.getTypeList();
      this.getFactoryList();
      getWarehouseList().then((res) => {
        this.warehouseList = res;
      });
    },
    filters: {},
    methods: {
      /* 表格数据源 */
      datasource({ page, limit, where }) {
        // console.log(where.planDeliveryTime, 'www');
        let startTime = undefined;
        let endTime = undefined;
        if (where.planDeliveryTime) {
          startTime = where.planDeliveryTime[0];
          endTime = where.planDeliveryTime[1];
        }
        return getList({
          pageNum: page,
          size: limit,
          ...where,
          startTime,
          endTime
        });
      },

      open(type, row) {
        this.$refs.create.open(type, row);
      },

      handleTabClick(e) {
        this.tabValue = e.name;
        this.reload();
      },

      async getTypeList() {
        let res = await getByCode('entrust_type');
        if (res?.code == 0) {
          console.log(res);
          let list = res.data.map((item) => {
            let key = Object.keys(item)[0];
            return { value: Number(key), label: item[key] };
          });
          this.typeList = list;
        }

        console.log(this.typeList, 'this.typeList');
      },

      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 || [];
      },
      async salesToProductionOpen(type) {
        const actionText = type == 1 ? '转生产计划' : '转生产订单';
        if (this.selection.length == 0) {
          return this.$message.warning('请选择一条数据');
        }

        if (type == 2 && this.selection.length > 1) {
          return this.$message.warning('只能选择一条数据');
        }

        const unreceived = this.selection.find(
          (item) => item.approvalStatus == 2 && item.sendStatus != 2
        );
        if (unreceived) {
          return this.$message.warning(`请先收货再${actionText}`);
        }

        const converted = this.selection.find(
          (item) =>
            item.changeType == 1 || item.changeType == 2 || item.changeType == 3
        );
        if (converted) {
          return this.$message.warning('该委托工单已转换，不能重复转换');
        }

        if (type == 2) {
          this.$refs.createOrderRef.open(this.selection);
          return;
        }

        const ids = this.selection.map((item) => item.id);
        try {
          await this.$confirm(
            `确认将已勾选的 ${ids.length} 条数据转为生产计划吗？`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          );
          this.loading = true;
          await transferProductionPlan(ids);
          this.$message.success('转生产计划成功');
          this.reload();
        } catch (err) {
          if (err !== 'cancel' && err !== 'close') {
            this.$message.error(err.message || '转生产计划失败');
          }
        } finally {
          this.loading = false;
        }
      },

      update(id) {
        update({ id, status: 1 }).then((res) => {
          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;
        });
      },
      /* 刷新表格 */
      reload(where) {
        const queryWhere = { ...(where || {}) };
        if (this.tabValue === '2') {
          queryWhere.preStatus = 1;
        } else {
          delete queryWhere.preStatus;
        }
        this.$nextTick(() => {
          this.$refs.table.reload({ page: 1, where: queryWhere });
        });
      },

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

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

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

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

<style lang="scss" scoped>
  .btn_box {
    margin-bottom: 6px;
  }
</style>
