<template>
  <div>
    <!-- <el-card shadow="never" v-loading="loading"> -->
    <!-- <search @search="reload" ref="searchRef"> </search> -->
    <div>
      <el-tabs type="card" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="委外" name="1"></el-tab-pane>
        <el-tab-pane label="请托" name="2"></el-tab-pane>
      </el-tabs>
    </div>

    <!-- 数据表格 -->
    <ele-pro-table
      ref="table"
      :columns="columns"
      :datasource="dataList"
      cache-key="workOrderTable"
      max-height="61vh"
      :need-page="false"
      v-if="activeName == '1'"
      @refresh="refresh"
    >
      <template v-slot:toolbar>
        <div class="rx-sc">
          <div class="c_title">委外记录 </div>
          <el-button
            type="primary"
            size="mini"
            style="margin: 0 5px"
            @click="handleAdd"
            >新增</el-button
          >
        </div>
      </template>
      <!-- <template v-slot:code="{ row }">
          <el-link
            type="primary"
            :underline="false"
            @click="handleDetails(row)"
            >{{ row.code }}</el-link
          >
        </template> -->

      <template v-slot:totalWeight="{ row }">
        <div v-if="row.totalWeight">{{ row.totalWeight }}</div>
        <div v-else>无</div>
      </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:isLast="{ row }">
        <el-tag v-if="row.isLast == 0">否</el-tag>
        <el-tag v-if="row.isLast == 1" type="success">是</el-tag>
      </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>
        <div v-if="row.type == 4">带料委外</div>
        <div v-if="row.type == 5">不带料委外</div>
      </template>

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

      <template v-slot:outsourceScene="{ row }">
        <span>{{ row.outsourceScene | outsourceSceneText }}</span>
      </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>

      <template v-slot:action="{ row }">
        <el-link type="primary" :underline="false" @click="handleDetails(row)">
          详情
        </el-link>

        <!-- <el-link
            type="primary"
            v-if="row.status == 1"
            :underline="false"
            @click="handleFlow(row)"
          >
            流程
          </el-link> -->
        <!--
          <el-link
            type="primary"
            v-if="row.status != 1"
            :underline="false"
            @click="handleRelease(row)"
          >
            提交
          </el-link> -->
      </template>
    </ele-pro-table>
    <!-- </el-card> -->

    <ele-pro-table
      ref="tableTwo"
      :columns="colunms1"
      :datasource="pleaseData"
      cache-key="workOrderTable"
      max-height="61vh"
      :need-page="false"
      v-if="activeName == '2'"
      @refresh="refresh"
    >
      <template v-slot:toolbar>
        <div class="rx-sc">
          <div class="c_title">请托记录 </div>
          <el-button
            type="primary"
            size="mini"
            style="margin: 0 5px"
            @click="handleAdd"
            >新增</el-button
          >
        </div>
      </template>

      <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 == 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:action="{ row }">
        <el-link
          type="primary"
          v-if="
            row.status == 0 &&
            row.approvalStatus != 1 &&
            row.approvalStatus != 2
          "
          :underline="false"
          @click="open('edit', row)"
        >
          编辑
        </el-link>
        <el-popconfirm
          class="ele-action"
          v-if="
            row.status == 0 &&
            row.approvalStatus != 1 &&
            row.approvalStatus != 2
          "
          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.status == 0 &&
            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 == 7
              || row.sendStatus == 8 || 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.sendOutQuantity > 0
          "
        >
          发货详情
        </el-link>

        <el-link
          type="primary"
          :underline="false"
          @click="handleFlow(row)"
          v-if="row.approvalStatus == 1 || row.approvalStatus == 2"
        >
          流程
        </el-link>
      </template>
    </ele-pro-table>

    <flow ref="flowRef"></flow>

    <release ref="releaseRef" @refreshs="releaseRefresh"></release>
    <detail ref="detailsRef"></detail>

    <timeDialog ref="timeDialogRef"></timeDialog>
    <goodsDetail ref="goodsDetailRef" @done="reloads"></goodsDetail>

    <Create ref="create" @refresh="reloads" />
  </div>
</template>

<script>
  import { getList } from '@/api/outsourcing/index.js';
  import flow from '../../../outsourcing/components/flow.vue';
  import search from '../../../outsourcing/components/search.vue';
  import release from '../../../outsourcing/components/release.vue';
  import Detail from '../../../outsourcing/components/details.vue';
  import dictMixins from '@/mixins/dictMixins';
  import timeDialog from '../../../outsourcing/components/timeDialog.vue';
  import { getFile } from '@/api/system/file';
  import { getList as getPleaseListData } from '@/api/entrust/index';
  import { getByCode } from '@/api/system/dictionary-data';
  import Create from '@/views/entrust/components/create.vue';
  import goodsDetail from '@/views/entrust/components/goodsDetail.vue';
  import { remove, submit, warehouseEntry } from '@/api/entrust/index.js';
  export default {
    components: {
      search,
      flow,
      release,
      Detail,
      timeDialog,
      Create,
      goodsDetail
    },

    props: {
      chooseType: {
        type: String,
        default: '1'
      }
    },

    mixins: [dictMixins],

    data() {
      return {
        loading: false,
        code: '',
        dataList: [],
        workOrderCode: '',
        activeName: this.chooseType,
        pleaseData: [],
        pleaseTypeList: []
      };
    },
    filters: {
      outsourceSceneText(text) {
        switch (text) {
          case 1:
            return '首工序委外';
          case 2:
            return '单工序';
          case 3:
            return '多工序';
          case 4:
            return '首工序及多工序';
          default:
            return '';
        }
      }
    },
    computed: {
      // 表格列配置
      columns() {
        return [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left',
            showOverflowTooltip: true
          },

          {
            prop: 'batchNo',
            label: '批次号',
            align: 'center',
            minWidth: 100,
            showOverflowTooltip: true
          },
          {
            slot: 'code',
            prop: 'code',
            label: '委外单编码',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'name',
            label: '委外单名称',
            align: 'center',
            showOverflowTooltip: true
          },

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

          {
            prop: 'taskName',
            label: '委外发起工序',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'taskNames',
            label: '委外工序',
            align: 'center',
            showOverflowTooltip: true
          },

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

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

          {
            slot: 'type',
            label: '委外类型',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'outsourceScene',
            slot: 'outsourceScene',
            label: '委外场景',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'supplierName',
            label: '委外单位',
            align: 'center',
            showOverflowTooltip: true
          },

          {
            slot: 'requireDeliveryTime',
            label: '预计到货日期',
            align: 'center',
            width: 100,
            showOverflowTooltip: true
          },

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

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

          {
            prop: 'createTime',
            label: '创建时间',
            align: 'center',
            width: 100,
            showOverflowTooltip: true
          },

          {
            slot: 'status',
            label: '单据状态',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            label: '是否尾工序',
            slot: 'isLast',
            prop: 'isLast',
            minWidth: 100
          },
          {
            slot: 'approvalStatus',
            label: '审核状态',
            align: 'center',
            showOverflowTooltip: true
          },

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

          {
            label: '附件',
            slot: 'files',
            action: 'files',
            minWidth: 100,
            showOverflowTooltip: true
          },

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

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

      colunms1() {
        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: 100
          },

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

      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      }
    },
    created() {
      this.requestDict('请托类型');
    },

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

    methods: {
      statusFormatter(status) {
        const obj = this.statusOpt.find((i) => i.value == status);
        return obj && obj.label;
      },
      /* 表格数据源 */
      // datasource() {
      //   return getList({
      //     pageNum: 1,
      //     size: -1,
      //     workOrderCode: this.code
      //   });
      // },

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

      remove(id) {
        let ids = id || this.selection.map((item) => item.id);
        remove(ids).then((res) => {
          this.$message.success('删除' + res);
          this.reloads();
        });
      },

      submit(item) {
        const beEntrustedDeptId = item && item.beEntrustedDeptId;
        if (
          beEntrustedDeptId === null ||
          beEntrustedDeptId === undefined ||
          (typeof beEntrustedDeptId === 'string' &&
            beEntrustedDeptId.trim() === '')
        ) {
          this.$message.warning('请先完善请托单的受托部门信息');
          return;
        }
        this.$confirm('是否提交该请托单的审核流程?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            submit({
              businessId: item.id,
              beEntrustedDeptId
            }).then((res) => {
              this.$message.success('提交' + res.message);
              this.reloads();
            });
          })
          .catch(() => {});
      },

      getPleaseType(item) {
        const data = this.pleaseTypeList.filter((it) => it.value == item.type);

        return data.length != 0 ? data[0].label : '';
      },

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

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

      async getDataList(code) {
        this.workOrderCode = code;
        await getList({
          pageNum: 1,
          size: -1,
          workOrderCode: this.workOrderCode
        }).then((res) => {
          console.log(res);
          this.dataList = res.list || [];
          // this.$forceUpdate();
        });
      },

      async getPleaseData(code) {
        this.workOrderCode = code;
        await getPleaseListData({
          pageNum: 1,
          size: -1,
          workOrderCode: this.workOrderCode
        }).then((res) => {
          this.pleaseData = res.list || [];
        });
      },

      downloadFile(file) {
        getFile({ objectName: file.storePath }, file.name);
      },

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

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

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

      reloads() {
        this.$nextTick(() => {
          this.getPleaseData(this.workOrderCode);
        });
      },

      handleRelease(row) {
        this.$refs.releaseRef.open(row);
      },

      handleClick(tab) {
        this.activeName = tab._props.name;

        if (this.activeName == '1') {
          this.getDataList(this.workOrderCode);
        } else if (this.activeName == '2') {
          this.getPleaseData(this.workOrderCode);
        }
      },

      openPleaseDetail() {},

      /* 刷新表格 */
      reload() {
        console.log('999');
        this.$nextTick(() => {
          if (this.activeName == '2') {
            this.getPleaseData(this.workOrderCode);
          } else {
            this.getDataList(this.workOrderCode);
          }
        });
      },
      refresh() {
        this.$nextTick(() => {
          if (this.activeName == '2') {
            this.getPleaseData(this.workOrderCode);
          } else {
            this.getDataList(this.workOrderCode);
          }
        });
      },

      handleAdd() {
        // this.$refs.releaseRef.open();
        this.$emit('outsourcingAdd', 'pick', this.activeName);
      },

      releaseRefresh() {
        this.$refs.table.reload();
      }
    }
  };
</script>

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