<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <ele-split-layout
        :width="contactData?.id || businessOpportunityData?.id ? '0' : '210px'"
        allow-collapse
        :right-style="{ overflow: 'hidden' }"
      >
        <div>
          <div class="ele-border-lighter sys-organization-list">
            <AssetTree
              @handleNodeClick="handleNodeClick"
              id="20"
              :isFirstRefreshTable="false"
              ref="treeList"
            />
          </div>
        </div>
        <template v-slot:content>
          <div class="ele-border-lighter form-content" v-loading="loading">
            <search-contract @search="reload"></search-contract>

            <!-- 数据表格 -->
            <ele-pro-table
              ref="table"
              :columns="columns"
              :datasource="datasource"
              height="calc(100vh - 375px)"
              full-height="calc(100vh - 116px)"
              tool-class="ele-toolbar-form"
              :selection.sync="selection"
              :page-size="20"
              @columns-change="handleColumnChange"
              :cache-key="cacheKeyUrl"
            >
              <!-- 表头工具栏 -->
              <template v-slot:toolbar>
                <div class="flex-end">
                  <div>
                    <el-button
                      size="small"
                      type="primary"
                      icon="el-icon-plus"
                      class="ele-btn-icon"
                      @click="openEdit('add', {})"
                    >
                      新建
                    </el-button>

                    <el-button
                      size="small"
                      type="danger"
                      el-icon-delete
                      class="ele-btn-icon"
                      @click="allDelBtn"
                      :disabled="selection?.length === 0"
                    >
                      批量删除
                    </el-button>
                  </div>
                  <div class="title">
                    合同总金额：{{ extInfo.contractTotalPrice }}元
                  </div>
                </div>
              </template>

              <!-- 查看详情列 -->
              <template v-slot:contractName="{ row }">
                <el-link
                  type="primary"
                  :underline="false"
                  @click="openDetail(row)"
                >
                  {{ row.contractName }}
                </el-link>
              </template>

              <!-- 操作列 -->
              <template v-slot:action="{ row }">
                <el-link
                  type="primary"
                  v-if="
                    (isNeed_process_is_close && [0, 3].includes(row.status)) ||
                    !isNeed_process_is_close
                  "
                  :underline="false"
                  icon="el-icon-edit"
                  @click="openEdit('edit', row)"
                >
                  修改
                </el-link>
                <el-link
                  type="primary"
                  v-if="isNeed_process_is_close && [0, 3].includes(row.status)"
                  :underline="false"
                  icon="el-icon-plus"
                  @click="contractBookSubmit(row)"
                >
                  提交
                </el-link>
                <el-link
                  type="primary"
                  v-if="[2].includes(row.status) && !row.hasGeneratedOrder"
                  :underline="false"
                  icon="el-icon-plus"
                  @click="handleGenerateOrder(row)"
                >
                  生成订单
                </el-link>
                <el-link
                  type="primary"
                  v-if="[2].includes(row.status) && !row.hasInvoiceApply"
                  :underline="false"
                  icon="el-icon-plus"
                  @click="invoiceManage(row)"
                >
                  新增发票
                </el-link>

                <jimureport
                  v-if="[2].includes(row.status)"
                  :businessId="row.id"
                  businessCode="erpcontractprint"
                  style="margin-left: 5px"
                ></jimureport>
                <el-popconfirm
                  v-if="
                    (isNeed_process_is_close && [0, 3].includes(row.status)) ||
                    !isNeed_process_is_close
                  "
                  class="ele-action"
                  title="确定要删除此信息吗？"
                  @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>
          </div>
        </template>
      </ele-split-layout>
    </el-card>

    <add-dialog
      ref="addDialogRef"
      @done="reload"
      :categoryTreeList="treeList"
      :contactData="contactData"
      :businessOpportunityData="businessOpportunityData"
      :curNodeData="curNodeData"
      :isRequired="isRequired"
    ></add-dialog>
    <detail-dialog ref="contactDetailDialogRef"></detail-dialog>
    <!-- 多选删除弹窗 -->
    <pop-modal
      :visible.sync="delVisible"
      content="是否确定删除？"
      @done="commitBtn"
    />
    <saleOrderAddDialog
      ref="saleOrderAddDialogRef"
      @done="reload"
    ></saleOrderAddDialog>
    <supplierAddDialog
      ref="supplierAddDialogRef"
      @done="reload"
    ></supplierAddDialog>
    <autogenerate-dialog
      ref="autogenerateDialogRef"
      @handleSubmit="saleOrderSubmit"
      @reload="reload"
    ></autogenerate-dialog>
    <process-submit-dialog
      api-fun-name="contractStatusAPI"
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="reload"
    ></process-submit-dialog>
    <addInvoiceManage
      :add-or-edit-dialog-flag.sync="addOrEditDialogFlag"
      ref="addOrEditDialogRef"
      v-if="addOrEditDialogFlag"
      @reload="reload"
    ></addInvoiceManage>
  </div>
</template>

<script>
  import searchContract from './components/searchContract.vue';
  import addDialog from './components/addDialog.vue';
  import detailDialog from './components/detailDialog.vue';
  import popModal from '@/components/pop-modal';
  import jimureport from '@/components/jimureport/browseModal.vue';

  import AssetTree from '@/components/AssetTree';
  import { reviewStatus } from '@/enum/dict';
  import { contactTypeTree } from '@/api/saleManage/contact';
  import saleOrderAddDialog from '@/views/saleManage/saleOrder/components/addDialog.vue';
  import supplierAddDialog from '@/views/purchasingManage/purchaseOrder/components/addDialog.vue';
  import { submit as saleOrderSubmitAPI } from '@/api/saleManage/saleorder';
  import tabMixins from '@/mixins/tableColumnsMixin';
  import {
    getTableList,
    submit,
    deleteInformation,
    batchSubmitAPI
  } from '@/api/contractManage/contractBook';
  import dictMixins from '@/mixins/dictMixins';
  import autogenerateDialog from '@/BIZComponents/autogenerateDialog.vue';
  import processSubmitDialog from '@/BIZComponents/processSubmitDialog/processSubmitDialog.vue';
  import addInvoiceManage from '@/views/financialManage/invoiceManage/components/addOrEditDialog.vue';

  import { parameterGetByCode } from '@/api/main/index.js';

  export default {
    mixins: [dictMixins, tabMixins],
    components: {
      processSubmitDialog,
      autogenerateDialog,
      AssetTree,
      searchContract,
      popModal,
      addDialog,
      detailDialog,
      saleOrderAddDialog,
      supplierAddDialog,
      addInvoiceManage,
      jimureport
    },
    //客户管理数据
    props: {
      contactData: {
        type: Object,
        default: () => {
          return {};
        }
      },
      businessOpportunityData: {
        type: Object,
        default: () => {
          return {};
        }
      }
    },
    data() {
      return {
        selection: [], //单选中集合
        delVisible: false, //批量删除弹框状态
        loading: false, // 加载状态
        processSubmitDialogFlag: false,
        addOrEditDialogFlag: false,
        treeList: [], //左边分类数据
        extInfo: {},
        columns: [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center'
          },
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'contractName',
            label: '合同名称',
            align: 'center',
            slot: 'contractName',
            showOverflowTooltip: true,
            minWidth: 200
          },
          {
            prop: 'categoryName',
            label: '合同分类',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'dversion',
            label: '版本号',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 80
          },
          {
            prop: 'productNames',
            label: '产品名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'partaName',
            label: '甲方名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150
          },
          {
            prop: 'partaLinkName',
            label: '甲方联系人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 130
          },

          {
            prop: 'partaTel',
            label: '甲方联系电话',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 130
          },
          {
            prop: 'partbName',
            label: '乙方名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 130
          },
          {
            prop: 'partbLinkName',
            label: '乙方联系人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 130
          },
          {
            prop: 'partbTel',
            label: '乙方联系电话',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 130
          },

          {
            prop: 'contractNo',
            label: '编码',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 170
          },
          {
            prop: 'contractNumber',
            label: '合同编号',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 200
          },

          {
            prop: 'enabled',
            label: '是否可用',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140,
            formatter: (_row, _column, cellValue) => {
              return _row.enabled ? '是' : '否';
            }
          },
          {
            prop: 'contractStartDate',
            label: '签订日期',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'contractEndDate',
            label: '结束日期',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'receiptPaymentType',
            label: '收付款类型',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 130,
            formatter: (_row, _column, cellValue) => {
              return _row.receiptPaymentType == 1 ? '固定' : '分期';
            }
          },
          {
            prop: 'discountTotalPrice',
            label: '合同总金额',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 130
          },

          {
            prop: 'status',
            label: '审核状态',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100,
            formatter: (_row, _column, cellValue) => {
              return reviewStatus[_row.status];
            }
          },
          {
            prop: 'createUsername',
            label: '创建人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 120
          },
          {
            prop: 'createTime',
            label: '创建时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 250,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true,
            fixed: 'right'
          }
        ],
        cacheKeyUrl: 'eos-2310d377-contract-contractBook',
        curNodeData: {},
        isRequired: true,
      };
    },
    computed: {},
    created() {
      this.requestDict('客户状态');
      this.getTreeData();

      parameterGetByCode({
        code: 'order_person_info'
      }).then((res) => {
        this.isRequired = Boolean(res.value);
      });

      if (this.$route.query.isView) {
        this.$nextTick(() => {
          this.openDetail({
            id: this.$route.query.id
          });
          const url = new URL(window.location.href);
          url.search = ''; // 清空查询参数
          window.history.pushState({}, '', url.href);
        });
      }
    },
    methods: {
      //点击左边分类
      handleNodeClick(data, node) {
        if (node.level != 1) {
          this.curNodeData = data;
          this.curNodeData.level = node.level;
          this.curNodeData['parentCode'] =
            node.level == 3 ? node.parent.data.code : '';
        }

        this.reload({ categoryId: data.id });
      },
      /* 表格数据源 */
      async datasource({ page, limit, where, order }) {
        if (this.businessOpportunityData.id) {
          where['opportunityId'] = this.businessOpportunityData.id;
        }
        if (this.contactData.id) {
          where['contactId'] = this.contactData.id;
        }
        const data = await getTableList({
          pageNum: page,
          size: limit,
          ...where
        });
        this.extInfo = data.extInfo;
        return data;
      },

      //获取左边分类
      async getTreeData() {
        try {
          this.treeLoading = true;
          const res = await contactTypeTree({ id: '20' });
          this.treeLoading = false;
          if (res?.code === '0') {
            this.treeList = res.data;
            return this.treeList;
          }
        } catch (error) {}
        this.treeLoading = false;
      },
      /* 刷新表格 */
      reload(where) {
        this.$refs.table.reload({ page: 1, where });
      },
      invoiceManage(row) {
        this.addOrEditDialogFlag = true;
        this.$nextTick(() => {
          this.$refs.addOrEditDialogRef.createInvoice1(row, row.type, 2);
        });
      },
      //新增编辑
      openEdit(type, row) {
        this.$refs.addDialogRef.open(type, row);
        this.$refs.addDialogRef.$refs.form &&
          this.$refs.addDialogRef.$refs.form.clearValidate();
      },

      //批量删除
      allDelBtn() {
        if (this.selection.length === 0) return;
        let flag = this.selection.some((item) => [1, 2].includes(item.status));
        if (flag)
          return this.$message.warning(
            '抱歉已审核、审核中的数据不能删除,请检查'
          );
        this.delVisible = true;
      },

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

      //删除弹框确定
      commitBtn() {
        const dataId = this.selection.map((v) => v.id);
        this.remove(dataId);
      },
      contractBookSubmit(res) {
        this.processSubmitDialogFlag = true;
        let key =
          res.type == 1 ? 'sales_contract_approve' : 'contract_approve_2';
        this.$nextTick(() => {
          let params = {
            businessId: res.id,
            businessKey: key,
            formCreateUserId: res.createUserId,
            variables: {
              businessType: res.categoryName,
              businessCode: res.contractNumber,
              businessName: res.contractName
            }
          };
          this.$refs.processSubmitDialogRef.init(params);
        });
        // submit({
        //   businessId: res.id,
        //   businessType: res.type
        // }).then((res) => {
        //   this.$message.success('提交成功！');
        //   this.reload();
        // });
      },
      contractBatchSubmit() {
        if (this.selection.some((item) => ![0, 3].includes(item.status)))
          return this.$message.warning(
            '审核中、已提交数据不能再次提交，请检查'
          );
        let arr = this.selection.map((item) => {
          return {
            businessId: item.id,
            businessType: item.type
          };
        });
        batchSubmitAPI(arr).then((res) => {
          this.$message.success('提交成功！');
          this.reload();
        });
      },
      //
      handleGenerateOrder(row) {
        //1销售2是采购
        let refName =
          row.type == '1' ? 'saleOrderAddDialogRef' : 'supplierAddDialogRef';
        this.$refs[refName].contractOpen(row);
        this.$refs[refName].$refs.form &&
          this.$refs[refName].$refs.form.clearValidate();
      },
      //销售订单审批
      saleOrderSubmit(id) {
        saleOrderSubmitAPI({
          businessId: id
        }).then(() => {
          this.$refs.saleOrderAddDialogRef &&
            this.$refs.saleOrderAddDialogRef.cancel();
          this.$message.success('提交成功');
          this.reload();
        });
      },
      //查看详情
      openDetail(row) {
        this.$refs.contactDetailDialogRef.open(row);
      }
    }
  };
</script>

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

  .sys-organization-list {
    height: calc(100vh - 225px);
    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;
    }
  }
  .flex-end {
    display: flex;
    align-items: center;
    .title {
      font-size: 14px;
      flex: 1;
      display: flex;
      padding-right: 20px;
      justify-content: flex-end;
    }
  }
</style>
