<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <div class="ele-border-lighter form-content" v-loading="loading">
        <opportunity-search @search="reload"> </opportunity-search>

        <!-- 数据表格 -->
        <ele-pro-table
          ref="table"
          :columns="columns"
          :datasource="datasource"
          height="calc(100vh - 365px)"
          full-height="calc(100vh - 116px)"
          tool-class="ele-toolbar-form"
          :selection.sync="selection"
          :row-class-name="tableRowClassName"
          :page-size="20"
          @columns-change="handleColumnChange"
          :cache-key="cacheKeyUrl"
        >
          <!-- 表头工具栏 -->
          <template v-slot:toolbar>
            <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>
          </template>

          <template v-slot:name="{ row }">
            <el-link type="primary" :underline="false" @click="openDetail(row)">
              {{ row.name }}</el-link
            >
          </template>

          <!-- 操作列 -->
          <template v-slot:action="{ row }">
            <el-link
              type="primary"
              :underline="false"
              icon="el-icon-edit"
              @click="handleFollow(row)"
            >
              跟进
            </el-link>
            <el-link
              type="primary"
              :underline="false"
              icon="el-icon-edit"
              @click="assign(row)"
            >
              转派
            </el-link>
            <el-link
              type="primary"
              :underline="false"
              icon="el-icon-plus"
              v-if="[2].includes(row.approvalStatus) && row.hasQuote != 1"
              @click="addQuotation('add', row)"
            >
              生成报价
            </el-link>
            <el-link
              type="primary"
              :underline="false"
              icon="el-icon-edit"
              v-if="
                (isNeed_process_is_close &&
                  [0, 3].includes(row.approvalStatus)) ||
                !isNeed_process_is_close
              "
              @click="openEdit('edit', row)"
            >
              修改
            </el-link>
            <el-link
              type="primary"
              :underline="false"
              icon="el-icon-plus"
              @click="sub(row)"
              v-if="
                isNeed_process_is_close && [0, 3].includes(row.approvalStatus)
              "
            >
              提交
            </el-link>
            <el-link
              v-if="row.status === 2"
              type="primary"
              :underline="false"
              icon="el-icon-check"
              @click="enableOption(row)"
            >
              启用
            </el-link>
            <el-link
              v-if="row.status === 1"
              type="primary"
              :underline="false"
              icon="el-icon-close"
              @click="disableOption(row)"
            >
              禁用
            </el-link>

            <el-popconfirm
              class="ele-action"
              title="确定要删除此信息吗？"
              @confirm="remove(row)"
            >
              <template v-slot:reference>
                <el-link
                  type="danger"
                  :underline="false"
                  icon="el-icon-delete"
                  v-if="
                    (isNeed_process_is_close &&
                      [0, 3].includes(row.approvalStatus)) ||
                    !isNeed_process_is_close
                  "
                >
                  删除
                </el-link>
              </template>
            </el-popconfirm>
          </template>
        </ele-pro-table>
      </div>
    </el-card>

    <add-opportunity-dialog
      ref="addContactDialogRef"
      :categoryTreeList="treeList"
      :contactId="contactId"
      :contactName="contactName"
      @done="reload"
    ></add-opportunity-dialog>
    <addQuotation ref="quotationRef" @done="reload"></addQuotation>

    <opportunity-detail-dialog
      ref="contactDetailDialogRef"
    ></opportunity-detail-dialog>
    <follow-list ref="followDialogRef"></follow-list>
    <!-- 多选删除弹窗 -->
    <pop-modal
      :visible.sync="delVisible"
      content="是否确定删除？"
      @done="commitBtn"
    />
    <drawer ref="drawerRef"></drawer>
    <process-submit-dialog
      api-fun-name="businessOpportunityUpdateStatusAPI"
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="reload"
    ></process-submit-dialog>
    <assignDialog ref="assignDialogRef" @success="reload"></assignDialog>
  </div>
</template>

<script>
  import opportunitySearch from './components/opportunitySearch.vue';
  import drawer from './components/drawer.vue';
  import addOpportunityDialog from './components/addOpportunityDialog.vue';
  import addQuotation from '@/views/saleManage/quotation/components/addDialog.vue';
  import processSubmitDialog from '@/BIZComponents/processSubmitDialog/processSubmitDialog.vue';
  import opportunityDetailDialog from './components/opportunityDetailDialog.vue';
  import followList from './components/followList.vue';
  import popModal from '@/components/pop-modal';
  import {
    getTableList,
    submit,
    deleteInformation,
    updateStatus
  } from '@/api/saleManage/businessOpportunity';
  import dictMixins from '@/mixins/dictMixins';
  import assignDialog from './components/assignDialog';
  import { reviewStatus } from '@/enum/dict';
  import { businessOpportunityUpdateStatusAPI } from '@/BIZComponents/processSubmitDialog/api';
  import tabMixins from '@/mixins/tableColumnsMixin';

  export default {
    mixins: [dictMixins,tabMixins],
    components: {
      opportunitySearch,
      followList,
      popModal,
      addOpportunityDialog,
      opportunityDetailDialog,
      addQuotation,
      drawer,
      processSubmitDialog,
      assignDialog
    },
    props: {
      contactId: '',
      contactName: ''
    },
    data() {
      return {
        selection: [],
        delVisible: false,
        // 加载状态
        loading: false,
        processSubmitDialogFlag: false,
        columns: [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center'
          },
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'code',
            label: '商机编码',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 200,
            fixed: 'left'
          },
          {
            prop: 'name',
            label: '商机名称',
            align: 'center',
            slot: 'name',
            showOverflowTooltip: true,
            minWidth: 200,
            fixed: 'left'
          },

          {
            prop: 'contactName',
            label: '客户名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'productNames',
            label: '产品名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },

          {
            prop: 'sourceName',
            label: '商机来源',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'stageName',
            label: '商机阶段',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'stageChangeTime',
            label: '阶段变更时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'budget',
            label: '预算',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140,
            formatter: (_row, _column, cellValue) => {
              return _row.budget ? _row.budget + '万元' : '';
            }
          },
          {
            prop: 'winRate',
            label: '赢单率',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140,
            formatter: (_row, _column, cellValue) => {
              return _row.winRate ? _row.winRate + '%' : '';
            }
          },
          {
            prop: 'expectedSigningAmount',
            label: '预计签单金额',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140,
            formatter: (_row, _column, cellValue) => {
              return _row.expectedSigningAmount
                ? _row.expectedSigningAmount + '万元'
                : '';
            }
          },
          {
            prop: 'expectedClosingDate',
            label: '预计结单日期',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140,
            formatter: (_row, _column, cellValue) => {
              return _row.expectedClosingDate?.substr(0, 10) || '';
            }
          },

          {
            prop: 'periodOfValidity',
            label: '商机有效期',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140,
            formatter: (_row, _column, cellValue) => {
              return _row.periodOfValidity
                ? _row.periodOfValidity + '个月'
                : '';
            }
          },
          {
            prop: 'opportunityAssertTime',
            label: '商机生效时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'opportunityExpireTime',
            label: '商机失效时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'responsibleName',
            label: '负责人名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 120
          },

          {
            prop: 'status',
            label: '启用状态',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100,
            formatter: (_row, _column, cellValue) => {
              return _row.status === 1 ? '启用' : '禁用';
            }
          },
          {
            prop: 'approvalStatus',
            label: '审核状态',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100,
            formatter: (_row, _column, cellValue) => {
              return reviewStatus[_row.approvalStatus];
            }
          },
          {
            prop: 'createUserName',
            label: '创建人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 80
          },
          {
            prop: 'createTime',
            label: '创建时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 160,
            formatter: (_row, _column, cellValue) => {
              return this.$util.toDateString(cellValue);
            }
          },
          {
            prop: 'remark',
            label: '备注',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 120
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 350,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true,
            fixed: 'right'
          }
        ],
        current: {},
        curNodeData: {},
        treeList: [],
        treeLoading: false,
        formData: {},
        rootTreeId: null,
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        showEdit: true,
        cacheKeyUrl:"eos-eaf1548b-businessOpportunity"
      };
    },
    computed: {},
    created() {
      this.requestDict('客户状态');
    },
    methods: {
      businessOpportunityUpdateStatusAPI,
      /* 表格数据源 */
      datasource({ page, limit, where, order }) {
        if (this.contactId) {
          where['contactId'] = this.contactId;
        }
        return getTableList({
          pageNum: page,
          size: limit,
          ...where
        });
      },
      tableRowClassName({ row, rowIndex }) {
        if (row.opportunityExpireTime) {
          const time =
            (new Date(row.opportunityExpireTime).getTime() -
              new Date().getTime()) /
            1000 /
            60 /
            60 /
            24;
          return time <= 15 ? 'warning-row' : '';
        }
        return '';
      },
      /* 刷新表格 */
      reload(where) {
        this.$refs.table.reload({ page: 1, where });
      },
      assign(row) {
        this.$refs.assignDialogRef.open(row.id);
      },
      openEdit(type, row) {
        this.current = row;
        this.showEdit = true;
        this.$refs.addContactDialogRef.open(type, row, row.id);
        this.$refs.addContactDialogRef.$refs.form &&
          this.$refs.addContactDialogRef.$refs.form.clearValidate();
      },
      addQuotation(type, row) {
        this.$refs.quotationRef.open(type, row, row.id);
        this.$refs.quotationRef.$refs.form &&
          this.$refs.quotationRef.$refs.form.clearValidate();
      },
      //跟进
      handleFollow(row) {
        this.current = row;
        this.$refs.followDialogRef.open(row);
      },
      //批量删除
      allDelBtn() {
        if (this.selection.length === 0) return;
        let flag = this.selection.some((item) =>
          [1, 2].includes(item.approvalStatus)
        );
        if (flag)
          return this.$message.warning(
            '抱歉已审核、审核中的数据不能删除,请检查'
          );
        this.delVisible = true;
      },

      commitBtn() {
        const dataId = this.selection.map((v) => v.id);
        deleteInformation(dataId).then((res) => {
          this.$message.success('删除成功！');
          this.reload();
        });
      },
      remove(row) {
        deleteInformation([row.id]).then((res) => {
          this.$message.success('删除成功！');
          this.reload();
        });
      },
      /** 启用客户 */
      enableOption(row) {
        updateStatus(row.id, 1)
          .then((msg) => {
            this.$message.success('启用成功');
            this.reload();
          })
          .catch((e) => {
            this.$message.error(e.message);
          });
      },
      /** 禁用客户 */
      disableOption(row) {
        updateStatus(row.id, 2)
          .then((msg) => {
            this.$message.success('禁用成功');
            this.reload();
          })
          .catch((e) => {
            this.$message.error(e.message);
          });
      },
      sub(res) {
        this.processSubmitDialogFlag = true;
        this.$nextTick(() => {
          let params = {
            businessId: res.id,
            businessKey: 'business_opportunity_approve',
            formCreateUserId: res.createUserId,
            variables: {
              businessCode: res.code
            }

            // callBackMethodType : '1',
            // callBackMethod : 'proTargetPlanApproveApiImpl.updatePlanApprovalStatus',
            // pcHandle : '/bpm/handleTask/components/project-manage/plan-manage/submit.vue',
            // pcView : '/bpm/handleTask/components/project-manage/plan-manage/detailDialog.vue',
            // miniHandle : '',
            // miniView : '',
          };

          this.$refs.processSubmitDialogRef.init(params);
        });
        // submit({
        //   businessId: res.id
        // })
        //   .then((res) => {
        //     this.$message.success('提交成功');
        //     this.reload();
        //   })
        //   .catch((e) => {
        //     this.$message.error(e.message);
        //   });
      },
      openDetail(row) {
        // this.$refs.contactDetailDialogRef.open(row);
        this.$refs.drawerRef.open(row);
      }
    }
  };
</script>

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

  .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;
    }
  }
  :deep(.el-table) {
    .warning-row {
      background: oldlace;
    }
    .success-row {
      background: #f0f9eb;
    }
  }
</style>
