<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading" style="width: 100%">
      <!-- <div class="ele-border-lighter form-content" v-loading="loading"> -->
      <search-quotation @search="reload"></search-quotation>
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        height="calc(100vh - 375px)"
        full-height="calc(100vh - 116px)"
        tool-class="ele-toolbar-form"
        default-expand-all
        row-key="id"
        :tree-props="{
          children: 'sonPurchasePlanList',
          hasChildren: 'hasChildren'
        }"
        :page-size="20"
        @columns-change="handleColumnChange"
        :cache-key="cacheKeyUrl"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            v-if="!saleOrderData.id"
            class="ele-btn-icon"
            @click="openEdit('add', {})"
          >
            新建
          </el-button>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            v-if="
              saleOrderData.id &&
              saleOrderData.orderStatus == 2 &&
              saleOrderData.needProduce &&
              !!!saleOrderData.purchasePlanNum
            "
            class="ele-btn-icon"
            @click="handleAutoGenerate"
          >
            生成采购计划
          </el-button>
          <exportButton
            fileName="采购计划"
            apiUrl="/eom/purchaseplan/export"
            :params="params"
          ></exportButton>
        </template>

        <!-- 查看详情列 -->
        <template v-slot:planCode="{ row }">
          <el-link type="primary" :underline="false" @click="openDetail(row)">
            {{ row.planCode }}
          </el-link>
        </template>
        <template v-slot:requirementName="{ row }">
          <el-link
            type="primary"
            :underline="false"
            @click="openNeedDetail(row)"
          >
            {{ row.requirementName }}
          </el-link>
        </template>
        <template v-slot:action="{ row }">
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            v-if="
              (isNeed_process_is_close &&
                [0, 3].includes(row.status) &&
                !row.isCut) ||
              (!isNeed_process_is_close && !row.isCut)
            "
            @click="openEdit('edit', row)"
          >
            修改
          </el-link>
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            v-if="isNeed_process_is_close && [0, 3].includes(row.status)"
            @click="submitPlan(row)"
          >
            提交
          </el-link>
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            v-if="
              [2].includes(row.status) &&
              (!row.parentId || row.parentId == 0) &&
              [0].includes(row.progress) &&
              !orderSourceType.includes(row.sourceType) &&
              row.acceptUnpack == 1
            "
            @click="handleSplit(row)"
          >
            拆分
          </el-link>
          <el-link
            type="primary"
            :underline="false"
            v-if="
              [2].includes(row.status) &&
              (!row.isCut || (row.parentId && row.parentId != 0)) &&
              isAddInquiry == 0
            "
            icon="el-icon-plus"
            @click="addInquiry('add', row)"
          >
            生成核价单
          </el-link>
          <el-link
            type="primary"
            :underline="false"
            v-if="
              [2].includes(row.status) &&
              (!row.isCut || (row.parentId && row.parentId != 0)) &&
              isAddInquiry != 0 &&
              [0, 100, 101, 103].includes(row.progress)
            "
            icon="el-icon-plus"
            @click="addInquiry('add', row)"
          >
            生成核价单
          </el-link>
          <el-popconfirm
            class="ele-action"
            title="确定要删除此信息吗？"
            v-if="
              (isNeed_process_is_close &&
                [0, 3].includes(row.status) &&
                !row.isCut) ||
              (!isNeed_process_is_close && !row.isCut)
            "
            @confirm="remove([row.id])"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false" icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </el-card>

    <add-dialog
      :saleOrderData="saleOrderData"
      ref="addDialogRef"
      @done="reload"
    ></add-dialog>
    <detail-dialog ref="contactDetailDialogRef"></detail-dialog>
    <!-- 多选删除弹窗 -->
    <pop-modal
      content="是否确定删除？"
    />
    <detailNeedDialog ref="DetailNeedDialogRef"></detailNeedDialog>
    <split-dialog
      ref="splitDialogRef"
      v-if="splitDialogFlag"
      :splitDialogFlag.sync="splitDialogFlag"
      @done="reload"
    ></split-dialog>
    <autogenerate-dialog
      ref="autogenerateDialogRef"
      @reload="reload"
    ></autogenerate-dialog>
    <process-submit-dialog
      api-fun-name="purchaseplanStatusAPI"
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="reload"
    ></process-submit-dialog>
  </div>
</template>

<script>
  import searchQuotation from './components/searchQuotation.vue';
  import addDialog from './components/addDialog.vue';
  import addInquiryDialog from '../../purchasingManage/inquiryManage/components/addDialog.vue';
  import detailNeedDialog from '../../purchasingManage/purchaseNeedManage/components/detailDialog.vue';
  import detailDialog from './components/detailDialog.vue';
  import popModal from '@/components/pop-modal';
  import dictMixins from '@/mixins/dictMixins';
  import {
    getTableList,
    deleteInformation,
    isPlanPerson,
    getplanDetail
  } from '@/api/purchasingManage/purchasePlanManage';
  import splitDialog from './components/splitDialog.vue';
  import { purchasePlanProgressStatusEnum } from '@/enum/dict';
  import autogenerateDialog from '@/BIZComponents/autogenerateDialog.vue';
  import processSubmitDialog from '@/BIZComponents/processSubmitDialog/processSubmitDialog.vue';
  import { parameterGetByCode } from '@/api/main/index.js';
  import { orderSourceType } from '@/enum/dict';
  import exportButton from '@/components/upload/exportButton.vue';
  import { getWarehouseListByIds } from '@/api/purchasingManage/returnGoods';
  import { reviewStatus } from '@/enum/dict';
  import tabMixins from '@/mixins/tableColumnsMixin';

  export default {
    mixins: [dictMixins,tabMixins],
    components: {
      processSubmitDialog,
      searchQuotation,
      popModal,
      addDialog,
      detailDialog,
      detailNeedDialog,
      addInquiryDialog,
      splitDialog,
      autogenerateDialog,
      exportButton
    },
    data() {
      return {
        loading: false, // 加载状态
        processSubmitDialogFlag: false,
        splitDialogFlag: false, // 加载状态
        isAddInquiry: 0,
        orderSourceType,
        params: {},
        cacheKeyUrl: 'eos-c2e9664a-purchasingManage-purchasePlanManage',

      };
    },
    //客户管理数据
    props: {
      saleOrderData: {
        type: Object,
        default: () => {
          return {};
        }
      }
    },
    computed: {
      columns() {
        return [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left',
            className: 'backgroundWhite'
          },
          {
            prop: 'planCode',
            slot: 'planCode',
            label: '采购计划单编码',
            align: 'center',
            sortable: true,
            minWidth: 210
          },
          {
            prop: 'progress',
            label: '计划进度',
            align: 'center',
            showOverflowTooltip: true,
            formatter: (_row, _column, cellValue) => {
              return purchasePlanProgressStatusEnum.find(
                (val) => val.value == _row.progress
              )?.label;
            },
            minWidth: 200
          },
          {
            prop: 'planName',
            label: '采购计划单名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 200
          },
          {
            prop: 'requirementName',
            slot: 'requirementName',
            label: '采购需求单名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 200
          },
          {
            prop: 'productNames',
            label: '产品名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'batchNo',
            label: '批次号',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },

          {
            prop: 'sourceTypeName',
            label: '需求类型',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'requireDeptName',
            label: '需求部门',
            align: 'center',
            slot: 'requireDeptName',
            showOverflowTooltip: true,
            minWidth: 200
          },
          {
            prop: 'requireUserName',
            label: '需求人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'responsibleName',
            label: '负责人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 120
          },
          {
            prop: 'detailCount',
            label: '明细条数',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },

          {
            prop: 'createTime',
            label: '创建时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 180
          },
          {
            prop: 'status',
            label: '状态',
            align: 'center',
            formatter: (_row, _column, cellValue) => {
              return reviewStatus[cellValue];
            },
            showOverflowTooltip: true,
            minWidth: 120
          },

          {
            columnKey: 'action',
            label: '操作',
            width: 230,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true,
            fixed: 'right',
            className: 'backgroundWhite'
          }
        ];
      }
    },
    created() {
      this.requestDict('客户状态');
      // this.datasource();
      //采购管理采购计划是否可以重复生成核价单
      parameterGetByCode({
        code: 'purchasingManage_purchasePlanManage_isAddInquiry'
      }).then((res) => {
        this.isAddInquiry = res.value;
      });
    },
    methods: {
      /* 表格数据源 */
      datasource({ page, limit, where, order }) {
        if (this.saleOrderData.id) {
          where['saleOrderCode'] = this.saleOrderData.orderNo;
        }
        this.params = {
          pageNum: page,
          size: limit,
          ...where
        };
        return getTableList({
          pageNum: page,
          size: limit,
          ...where
        });
      },

      /* 刷新表格 */
      reload(where) {
        this.$refs.table.reload({ page: 1, where });
      },
      async submitPlan(row) {
        this.processSubmitDialogFlag = true;

        const data = await getplanDetail(row.id);
        let storemanIds = '';
        if (['3', '4', '5'].includes(row.sourceType)) {
          let ids = data.detailList.map((item) => item.warehouseId);
          let warehouseList = await getWarehouseListByIds(ids || []);
          storemanIds = warehouseList.map((item) => item.ownerId);
        }

        this.$nextTick(() => {
          let params = {
            businessId: row.id,
            businessKey: ['3', '4', '5'].includes(row.sourceType)
              ? 'outsource_purchasePlan_approve'
              : 'purchase_plan_approve',
            formCreateUserId: row.createUserId,
            variables: {
              businessCode: row.planCode,
              businessName: row.planName,
              businessType: row.sourceTypeName,
              storemanIds: storemanIds.toString()
            }
          };

          this.$refs.processSubmitDialogRef.init(params);
        });
      },
      //新增编辑
      openEdit(type, row) {
        this.$refs.addDialogRef.open(type, row, row.id);
        this.$refs.addDialogRef.$refs.form &&
          this.$refs.addDialogRef.$refs.form.clearValidate();
      },
      handleSplit(row) {
        this.splitDialogFlag = true;
        this.$nextTick(() => {
          this.$refs.splitDialogRef.init(row);
        });
      },
      //新增核价
      async addInquiry(type, row) {
        let code = await isPlanPerson(row.id);
        if (code == 1) {
          return this.$message.warning(
            '您不是该采购计划责任人，无法对该计划进行核价操作!'
          );
        }
        await this.$router.push({
          path: '/purchasingManage/inquiryManage/components/addDialog',
          query: {
            id: row.id ? row.id : null,
            type,
            t: new Date().getTime()
          }
        });
      },

      //删除接口
      remove(delData) {
        deleteInformation(delData).then((res) => {
          this.$message.success('删除成功！');
          this.reload();
        });
      },

      //查看详情
      openDetail(row) {
        this.$refs.contactDetailDialogRef.open(row);
      },
      //查看详情
      openNeedDetail(row) {
        this.$refs.DetailNeedDialogRef.open(row);
      },

      //生成
      handleAutoGenerate() {
        this.$refs.autogenerateDialogRef.init(this.saleOrderData.id, false);
      }
    }
  };
</script>

<style lang="scss" scoped>
  :deep(.el-link--inner) {
    margin-left: 0px !important;
  }
  // :deep(.is-hidden){
  //   background: #fff;
  // }

  .sys-organization-list {
    height: calc(100vh - 264px);
    box-sizing: border-box;
    border-width: 1px;
    border-style: solid;
    overflow: auto;
  }

  .sys-organization-list :deep(.el-tree-node__content) {
    height: 40px;

    & > .el-tree-node__expand-icon {
      margin-left: 10px;
    }
  }

  ::v-deep .el-pager li.active {
    color: #ffffff;
    background: #1890ff;
    border-radius: 50%;
    cursor: default;
  }

  ::v-deep .el-pager li {
    padding: 0 4px;
    background: var(--color-white);
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 28px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    margin: 0;
  }

  ::v-deep .el-table__row--level-1 {
    background: #e2f1ff61;
  }

  ::v-deep .el-table__row--level-0 {
    background: rgb(156 249 177);
  }
  :deep(.backgroundWhite) {
    background: white;
  }
</style>
