<script>
import { defineComponent } from 'vue'
export default defineComponent({
  beforeRouteEnter(to, from, next) {
    if (from.path != '/approvalUpdate' && from.path != '/approvalTurn' && from.path != '/updateCustom' && from.path != '/customDetail' && from.path != '/turnCustom') {
      sessionStorage.removeItem('approvalListBack')
    }
    next()
  }
})

</script>

<script setup>
import { ref, computed, onMounted } from "vue";
import { Search } from "@element-plus/icons-vue";
import { customInterence } from "@/api/api.js";
import { formatTime } from '@/utils/date'
import { onBeforeRouteLeave, useRouter } from "vue-router";
import ContractInfo from './components/ContractInfo.vue'
import CapprovalDia from './components/CapprovalDia.vue'

const router = useRouter()

onBeforeRouteLeave((to, form, next) => {
  let backData = {
    page_no: page_no.value,
    status: status.value,
    keyword: search_txt.value
  }
  sessionStorage.setItem('approvalListBack', JSON.stringify(backData))
  next()
})

const Role = computed(() => {
  return localStorage.getItem("Role") || "";
});

const RoleType = computed(() => {
  return localStorage.getItem("RoleType") || "";
});

/* 获取表格数据 */
const tableData = ref([]);
const pageSize = ref(10)
let page_no = ref(sessionStorage.getItem('approvalListBack') ? JSON.parse(sessionStorage.getItem('approvalListBack')).page_no : 1)
const total = ref(0)
const isShowloadding = ref(false);
function getTableData() {
  isShowloadding.value = true;
  let status = "";
  if (Role.value == "ficc_admin" || Role.value == "rai_admin") {
    status = status.value == "全部" ? "" : status.value;
  }
  customInterence
    .approvalList({
      PageSize: pageSize.value,
      CurrentIndex: page_no.value,
      Status: status,
      KeyWord: search_txt.value,
    })
    .then((res) => {
      isShowloadding.value = false;
      if (res.Ret === 200) {
        res.Data.List &&
          res.Data.List.forEach((item) => {
            item.StartDate = item.StartDate.replace(/-/g, ".");
            item.EndDate = item.EndDate.replace(/-/g, ".");
            item.FreezeStartDate = item.FreezeStartDate ? item.FreezeStartDate.replace(/-/g, ".") : "";
            item.FreezeEndDate = item.FreezeEndDate ? item.FreezeEndDate.replace(/-/g, ".") : "";
          });
        tableData.value = res.Data.List || [];
        total.value = res.Data.Paging.Totals;
      }
    });
}

onMounted(() => {
  if (sessionStorage.getItem('approvalListBack')) {
    let backData = JSON.parse(sessionStorage.getItem('approvalListBack'));
    search_txt.value = backData.keyword
    page_no.value = backData.page_no
    status.value = backData.status
  }
  getTableData()
});

// 状态改变
const status = ref("待审批");
const statusArr = ref(["全部", "待审批", "已审批"]);
function changeStatus() {
  page_no.value = 1
  getTableData()
}

//搜索
const search_txt = ref("");
function handlSearch() {
  status.value = '全部'
  page_no.value = 1
  getTableData()
}

function handleCurrentChange(page) {
  page_no.value = page
  getTableData()
}

/* 详情页 */
function goDetail(item) {
  router.push({
    path: '/customDetail',
    query: {
      id: item.CompanyId
    }
  })
}

// 申请转正、续约申请、补充协议 合同信息弹窗
const contractDialog = ref({
  show: false,
  cusdata: null,//客户信息（列表用户数据）
  type: '',//类型 申请转正、续约申请、补充协议
})
function contractInfoDialogClose() {
  contractDialog.value = {
    show: false,
    cusdata: null,//客户信息（列表用户数据）
    type: '',//类型 申请转正、续约申请、补充协议
  }
}

// 申请转正、续约申请、补充协议 选择合同类型弹窗 
const contractModel = ref({
  show: false,
  data: null,//客户信息（列表用户数据）
  type: '',//类型 申请转正、续约申请、补充协议
})
// 申请转正、续约申请、补充协议点击合同类型
function handleContractModel(e) {
  contractModel.value.show = false
  if (e === '非标准') {
    if (contractModel.value.type === '申请转正') {
      sessionStorage.setItem('companyInfo', JSON.stringify(contractModel.value.data))
      router.push({
        path: '/turnCustom',
        query: {
          isReapply: true
        }
      })
    } else if (contractModel.value.type === '续约申请') {
      sessionStorage.setItem('companyInfo', JSON.stringify(contractModel.value.data))
      router.push({
        path: '/updateCustom',
        query: {
          isReapply: true
        }
      })
    } else if (contractModel.value.type === '补充协议') {
      sessionStorage.setItem('companyInfo', JSON.stringify(contractModel.value.data))
      router.push({
        path: '/addAgreement',
        query: {
          isReapply: true
        }
      })
    }
    return
  }
  // 标准合同
  contractDialog.value.show = true
  contractDialog.value.type = contractModel.value.type
  contractDialog.value.cusdata = contractModel.value.data
}

/* 撤回 */
const isRetract = ref(false)
let revokeItem = null
function retractHandle(item) {
  revokeItem = item;
  customInterence.Revoke({
    CompanyId: item.CompanyId
  }).then(res => {
    isRetract.value = true;
    getTableData();
  })
}

/* 重新申请 */
const isApply = ref(false)//申请弹窗
const applyForm = ref({})//申请信息
const applyTit = ref('')//申请标题
function editHandle(item) {
  console.log(item);
  isRetract.value = false;
  /* 转正申请 */
  // ApplyContractType:申请合同类型  0 非标  1 标准
  if (item.ApplyMethod == 1) {
    contractModel.value = {
      show: false,
      data: item,
      type: '申请转正'
    }
    if (item.ApplyContractType == 0) {
      handleContractModel('非标准')
    } else {
      handleContractModel('标准')
    }

  } else if (item.ApplyMethod == 2 || item.ApplyMethod == 3 || item.ApplyMethod == 4) {
    applyForm.value = item;
    applyTit.value = item.ApplyMethod == 2 ? '申请解冻' : item.ApplyMethod == 3 ? '申请延期' : '申请领取';
    isApply.value = true;
    /* 续约申请 */
  } else if (item.ApplyMethod == 5) {
    contractModel.value = {
      show: false,
      data: item,
      type: '续约申请'
    }
    if (item.ApplyContractType == 0) {
      handleContractModel('非标准')
    } else {
      handleContractModel('标准')
    }
  } else if (item.ApplyMethod == 6) {
    contractModel.value = {
      show: false,
      data: item,
      type: '补充协议'
    }
    if (item.ApplyContractType == 0) {
      handleContractModel('非标准')
    } else {
      handleContractModel('标准')
    }
  }
}

const isReject = ref(false)//驳回弹窗
const rejectTxt = ref('')//驳回理由
/* 驳回理由弹窗 */
function openHandle(item) {
  rejectTxt.value = item.ApproveRemark;
  isReject.value = true;
}

const approvalInfo = ref({})//审批信息
const isApproval = ref(false)//审批弹窗
const approval_title = ref('')//审批标题
const isLookApproval = ref(false)//是否查看审批信息
function approvalOver() {
  isApproval.value = false
  getTableData()
}
/* 审批*/
function openApproval(item) {
  /* 转正审批 */
  if (item.ApplyMethod == 1) {
    sessionStorage.setItem('companyInfo', JSON.stringify(item));
    router.push({
      path: '/approvalTurn',
      query: {
        id: item.CompanyId,
        contractId: item.CompanyContractId
      }
    })
  } else if (item.ApplyMethod == 2 || item.ApplyMethod == 3 || item.ApplyMethod == 4) {//item.ApprovalCount
    approvalInfo.value = item;
    approval_title.value = item.ApplyMethod == 2 ? '解冻审批' : item.ApplyMethod == 3 ? '延期审批' : '领取审批';
    let str = item.ApprovalCount > 0 ? `(第${item.ApprovalCount}次申请)` : ''
    approval_title.value = approval_title.value + str
    isLookApproval.value = false;
    isApproval.value = true;
  } else if (item.ApplyMethod == 5 || item.ApplyMethod == 6) { // 续约审批
    sessionStorage.setItem('companyInfo', JSON.stringify(item));
    router.push({
      path: '/approvalUpdate',
      query: {
        id: item.CompanyId,
        contractId: item.CompanyContractId,
        ApplyMethod: item.ApplyMethod
      }
    })
  }
}
/* 查看审批信息 */
function openApprovalDtl(item) {
  /* 转正审批 */
  if (item.ApplyMethod == 1) {
    sessionStorage.setItem('companyInfo', JSON.stringify(item));
    router.push({
      path: '/approvalTurn',
      query: {
        id: item.CompanyId,
        contractId: item.CompanyContractId,
        isLook: true
      }
    })
  } else if (item.ApplyMethod == 2 || item.ApplyMethod == 3 || item.ApplyMethod == 4) {
    approvalInfo.value = item;
    // this.approval_title = item.ApplyMethod == 2?'解冻审批':item.ApplyMethod == 3?'延期审批'+(item.ApprovalCount!=0?'(第'+item.ApprovalCount+'次申请)':''):'领取审批';
    approval_title.value = item.ApplyMethod == 2 ? '解冻审批' : item.ApplyMethod == 3 ? '延期审批' : '领取审批';
    let str = item.ApprovalCount > 0 ? `(第${item.ApprovalCount}次申请)` : ''
    approval_title.value = approval_title.value + str
    isLookApproval.value = true;
    isApproval.value = true;
  } else if (item.ApplyMethod == 5) { // 续约审批
    sessionStorage.setItem('companyInfo', JSON.stringify(item));
    router.push({
      path: '/approvalUpdate',
      query: {
        id: item.CompanyId,
        contractId: item.CompanyContractId,
        isLook: true
      }
    })
  }
}

/* 取消 */
function cancelHandle(type) {
  if (type === 1) {
    isRetract.value = false
  } else if (type === 2) {
    isReject.value = false
  } else if (type === 3) {
    isApproval.value = false
  }
}



</script>

<template>
  <div class="approvalList_container">
    <div class="approvalList_top">
      <el-select
        v-model="status"
        placeholder="请选择状态"
        style="width: 200px; margin-right: 16px"
        @change="changeStatus"
        v-if="Role == 'ficc_admin' || Role == 'rai_admin'"
      >
        <el-option
          v-for="item in statusArr"
          :key="item"
          :label="item"
          :value="item"
        >
        </el-option>
      </el-select>
      <el-input
        placeholder="公司名称/信用代码"
        v-model="search_txt"
        @input="handlSearch"
        clearable
        style="max-width: 500px"
        :prefix-icon="Search"
      >
      </el-input>
    </div>
    <div class="approvalList_cont">
      <el-table
        ref="userTable"
        :data="tableData"
        v-loading="isShowloadding"
        element-loading-text="数据加载中..."
        border
      >
        <el-table-column prop="CompanyName" label="客户名称" align="center">
          <template #default="scope">
            <span
              style="color: #409eff; cursor: pointer"
              @click="goDetail(scope.row)"
              class="customName"
              >{{ scope.row.CompanyName }}</span
            ></template
          >
        </el-table-column>
        <el-table-column prop="CompanyType" label="客户类型" align="center">
          <template #default="scope">
            <span>{{ scope.row.CompanyType }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="IndustryName" label="所属行业" align="center">
          <template #default="scope">
            <span>{{ scope.row.IndustryName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="SellerName" label="所属销售" align="center">
          <template #default="scope">
            <span>{{ scope.row.SellerName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="ApprovalTime"
          label="提交审批时间"
          align="center"
        >
          <template #default="scope">
            <span>{{ formatTime(scope.row.ApprovalTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="CreateTime" label="审批时间" align="center">
          <template #default="scope">
            <span
              v-if="
                scope.row.ApproveStatus !== '待审批' &&
                scope.row.ApproveStatus !== '已撤回'
              "
              >{{ formatTime(scope.row.ApproveTime) }}
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="Status" label="客户状态" align="center">
          <template #default="scope">
            <span>{{ scope.row.Status }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="ApproveContent" label="待审内容" align="center">
          <template #default="scope">
            <span
              :style="
                Role == 'ficc_seller' || Role == 'rai_seller'
                  ? ''
                  : status == '已审批'
                  ? 'color:#666;'
                  : 'color:#F00;'
              "
              >{{ scope.row.ApproveContent }}</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="ApproveStatus" label="当前状态" align="center">
          <template #default="scope">
            <span
              :style="
                scope.row.ApproveStatus == '已审批'
                  ? ''
                  : scope.row.ApproveStatus == '已撤回'
                  ? 'color:#409EFF'
                  : 'color:#F00'
              "
              >{{
                scope.row.ApproveStatus == "驳回"
                  ? "已驳回"
                  : scope.row.ApproveStatus
              }}</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="ApproveStatus" label="申请人" align="center">
          <template #default="scope">
            <span
              :style="scope.row.ApproveStatus == '待审批' ? 'color:#F00' : ''"
              >{{ scope.row.ApplyRealName }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          min-width="110"
          v-if="Role != 'admin'"
        >
          <template #default="scope">
            <div style="color: #4099ef; font-size: 24px">
              <span
                class="editsty"
                style="marginright: 10px"
                @click="retractHandle(scope.row)"
                v-if="
                  scope.row.OpButton.Cancel &&
                  scope.row.ApproveStatus == '待审批'
                "
                >撤回</span
              >
              <template
                v-if="
                  scope.row.ApproveStatus == '驳回' &&
                  (Role == 'ficc_seller' || Role == 'rai_seller')
                "
              >
                <span
                  class="editsty"
                  style="marginright: 10px"
                  @click="openHandle(scope.row)"
                  >驳回理由</span
                >
                <span
                  class="editsty"
                  style="marginright: 10px"
                  @click="editHandle(scope.row)"
                  >重新申请</span
                >
              </template>
              <span
                class="editsty"
                style="marginright: 10px"
                @click="openApproval(scope.row)"
                v-if="
                  scope.row.OpButton.Approval &&
                  scope.row.ApproveStatus == '待审批'
                "
                >审批</span
              >
              <span
                class="editsty"
                @click="openApprovalDtl(scope.row)"
                v-if="
                  (Role == 'ficc_admin' || Role == 'rai_admin') &&
                  scope.row.ApproveStatus == '已审批'
                "
                >审批信息</span
              >
              <template
                v-if="
                  scope.row.ApproveStatus == '已撤回' &&
                  (Role == 'ficc_seller' || Role == 'rai_seller')
                "
              >
                <span
                  class="editsty"
                  style="marginright: 10px"
                  @click="editHandle(scope.row)"
                  >重新申请</span
                >
                <span
                  class="deletesty"
                  style="marginright: 10px"
                  @click="delHandle(scope.row)"
                  >删除</span
                >
              </template>
            </div>
          </template>
        </el-table-column>
        <template v-slot:empty>
          <div style="lineheight: 44px; margin: 60px 0; color: #999">
            <img
              src="~@/assets/img/cus_m/nodata.png"
              alt=""
              style="display: block; width: 160px; height: 128px; margin: auto"
            />
            <span>暂无数据</span>
          </div>
        </template>
      </el-table>
      <el-col :span="24" class="toolbar">
        <el-pagination
          layout="total,prev,pager,next,jumper"
          background
          :current-page="page_no"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :total="total"
          style="float: right"
        >
        </el-pagination>
      </el-col>
    </div>
  </div>

  <!-- 撤回弹窗 -->
  <el-dialog
    v-model="isRetract"
    :close-on-click-modal="false"
    :show-close="false"
    custom-class="appro_dialog"
    center
    width="22%"
  >
    <div
      style="
        display: flex;
        justify-content: center;
        alignitems: center;
        margin: 20px 0 50px;
        color: #606266;
        fontsize: 16px;
      "
    >
      <i
        class="el-icon-success"
        style="fontsize: 20px; color: #409eff; marginright: 10px"
      ></i>
      <span>撤回成功</span>
    </div>
    <div style="display: flex; justify-content: center; margin: 0 0 25px">
      <el-button
        type="primary"
        style="width: 112px; marginright: 24px"
        @click="editHandle(revokeItem)"
        >重新申请</el-button
      >
      <el-button
        style="width: 112px"
        @click="cancelHandle(1)"
        type="primary"
        plain
        >关闭</el-button
      >
    </div>
  </el-dialog>

  <!-- 驳回弹窗 -->
  <el-dialog
    title="驳回理由"
    v-model="isReject"
    :close-on-click-modal="false"
    custom-class="appro_dialog"
    @close="cancelHandle(2)"
    center
    top="20vh"
    width="22%"
  >
    <div style="display: flex; margin: 13px 0 50px; color: #606266">
      <span>{{ rejectTxt }}</span>
    </div>
    <div style="display: flex; justify-content: flex-end; margin: 0 0 26px">
      <el-button type="primary" style="width: 80px" @click="cancelHandle(2)"
        >知道了</el-button
      >
    </div>
  </el-dialog>

  <!-- 审批弹窗 -->
  <CapprovalDia
    :isLook="isLookApproval"
    :approvalInfo="approvalInfo"
    :isApproval="isApproval"
    :title="approval_title"
    @cancelHandle="cancelHandle(3)"
    @approvalOver="approvalOver"
  ></CapprovalDia>

  <!-- 申请转正、续约申请、补充协议标准合同模式下 合同信息弹窗 -->
  <ContractInfo
    :initData="contractDialog"
    @contractInfoDialogClose="contractInfoDialogClose"
  ></ContractInfo>
</template>

<style lang="scss" scoped>
.approvalList_container {
  .approvalList_top {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    border: 1px solid #ececec;
    padding: 20px 30px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
  }
  .approvalList_cont {
    min-height: calc(100vh - 260px);
    padding: 20px 30px 80px;
    background: #fff;
    margin-top: 20px;
    position: relative;
    border: 1px solid #ececec;
    border-radius: 4px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
  }
}
</style>
