<template>
  <div class="contractlist-container">
    <div class="top-wrap">
      <blcok v-if="RoleType === 'ficc_seller' || RoleType === 'rai_seller'"   style="margin-right:10px;">
        <el-button type="primary" @click="showAddTypeDia=true">添加合同</el-button>
        <el-button type="primary" plain @click="handleDownloadContractTemplate">合同操作指南</el-button>
      </blcok>
      <block v-if="!(RoleType === 'ficc_seller' || RoleType === 'rai_seller')" >
        <a :href="exportExcel" download>
          <el-button type="primary">下载EXCEL</el-button>
        </a>
      </block>

      <el-input placeholder="合同编号/客户名称/社会信用码" v-model="searchVal" style="max-width: 400px; float: right" @input="handleSearch" clearable>
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <el-select v-model="searchType" placeholder="请选择" style="width:120px;float: right;margin-right:10px">
        <el-option label="客户名称" value="使用方"></el-option>
        <el-option label="代付方" value="代付方"></el-option>
      </el-select>

    </div>
    <div class="list-wrap">
      <div style="margin-top: 10px; margin-bottom: 10px">
        <el-date-picker style="margin-bottom: 20px;margin-right:20px" v-model="timeRange" type="daterange" @change="handleSelectChange" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
        <el-select v-if="tabsActive==='业务合同'" clearable v-model="constractTypeVal" @change="handleSelectChange" placeholder="合同类型" style="margin-bottom: 20px;margin-right:20px">
          <el-option v-for="item in constractTypeOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <el-select clearable v-model="constractStatusVal" @change="handleSelectChange" placeholder="合同状态" style="margin-bottom: 20px;margin-right:20px">
          <el-option v-for="item in constractStatusOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <block v-if="RoleType === 'admin'||RoleType==='compliance'||RoleType==='finance'">
          <el-select clearable v-model="constractBelongVal" @change="handleSelectChange" placeholder="合同归属" style="margin-bottom: 20px;margin-right:20px">
            <el-option v-for="item in constractBelongOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
          <!-- <el-select clearable v-model="constractSellerVal" @change="handleSelectChange" placeholder="申请销售" style="margin-bottom: 20px;margin-right:20px">
            <el-option v-for="item in constractSellerOptions" :key="item.AdminId" :label="item.RealName" :value="item.AdminId"> </el-option>
          </el-select> -->
          <el-cascader
            v-model="constractSellerVal"
            placeholder="申请销售"
            style="min-width:225px;margin-bottom: 20px;margin-right:20px"
            :options="constractSellerOptions"
            :props="defaultSalesProps"
            :show-all-levels="false"
            collapse-tags
            clearable
            filterable
            @change="handleSelectChange">
          </el-cascader>
        </block>
      </div>
      <ul class="tabs-wrap">
        <li 
          v-for="item in tabs" 
          :class="['tab',{'act':tabsActive === item.name}]"
          @click="handleChangeTabs(item.name)"
        >{{item.name}}</li>
      </ul>
      <el-table :data="tableList" border ref="table">
        <el-table-column key="合同编号" align="center" prop="ContractCode" label="合同编号" width="160">
          <template slot-scope="scope">
            <span class="constract-sn" @click="handleGoDetail(scope.row.ContractBusinessType,scope.row.ContractId)">{{ scope.row.ContractCode }}</span>
          </template>
        </el-table-column>
        <el-table-column key="客户名称" align="center" prop="CompanyName" :label="tabsActive==='业务合同'?'客户名称':'代付方'"></el-table-column>
        <el-table-column key="社会信用码" align="center" prop="CreditCode" label="社会信用码" width="180"></el-table-column>
        <el-table-column key="代付方" align="center" prop="RelationContractList" :label="tabsActive==='业务合同'?'付款方':'客户名称'">
          <template slot-scope="scope">
            <div v-if="!scope.row.RelationContractList">{{scope.row.PayChannel=='无'?scope.row.CompanyName:scope.row.PayChannel}}</div>
            <div v-else style="color:#409eff;cursor: pointer" @click="handlePreviewContract(scope.row.RelationContractList)">
              <span v-if="scope.row.RelationContractList.length===1">{{scope.row.RelationContractList[0].CompanyName}}</span>
              <span v-else>查看</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column key="销售" align="center" prop="SellerName" label="销售" width="80"></el-table-column>
        <el-table-column key="合同类型" align="center" prop="ContractType" label="合同类型" width="80"></el-table-column>
        <el-table-column key="合同有效期" align="center" label="合同有效期" width="180">
          <template slot-scope="scope">{{ scope.row.StartDateStr|formatTime }}~{{ scope.row.EndDateStr|formatTime }}</template>
        </el-table-column>
        <el-table-column key="合同金额" align="center" prop="Price" :label="tabsActive==='业务合同'?'合同金额':'代付金额'" width="100">
          <template slot-scope="scope">{{ scope.row.Price|formatPriceHasPoint }}</template>
        </el-table-column>
        <el-table-column key="合同状态" align="center" prop="Status" label="合同状态" width="80">
          <template slot-scope="scope">
            <span :style="{ color: scope.row.Status === '已驳回'||scope.row.Status === '已解约' ? '#FF0000' : null }">{{ scope.row.Status }}</span>
          </template>
        </el-table-column>
        <el-table-column key="更新时间" align="center" prop="ModifyTimeStr" label="更新时间" width="160" :formatter="formatter"></el-table-column>
        <el-table-column key="seller操作" align="center" label="操作" width="200" v-if="RoleType === 'ficc_seller' || RoleType === 'rai_seller'">
          <template slot-scope="scope">
            <div v-if="scope.row.Status === '待提交'">
              <span class="btn" @click="handleOperation('submitApproval', scope.row)">提交审批</span>
              <span class="btn" @click="handleOperation('edit', scope.row)">编辑</span>
              <!-- <span class="btn" @click="handleOperation('downloadTem', scope.row)">草稿下载</span> -->
              <span class="btn" @click="handleOperation('delete', scope.row)" style="color: #ff0000">删除</span>
            </div>
            <div v-if="scope.row.Status === '待审批'">
              <span class="btn" @click="handleOperation('viewPackage', scope.row)">查看套餐</span>
              <span class="btn" @click="handleOperation('backApply', scope.row)" v-if="scope.row.OpButton.Cancel">撤回申请</span>
            </div>
            <div v-if="scope.row.Status === '已撤回'">
              <span class="btn" @click="handleOperation('viewPackage', scope.row)">查看套餐</span>
              <span class="btn" @click="handleOperation('modifyConstract', scope.row)">修改合同</span>
              <span class="btn" @click="handleOperation('delete', scope.row)" style="color: #ff0000">删除</span>
            </div>
            <div v-if="scope.row.Status === '已审批'">
              <span class="btn" @click="handleOperation('viewPackage', scope.row)">查看套餐</span>
              <span class="btn" @click="handleOperation('cancelConstract', scope.row)">作废合同</span>
              <span class="btn" @click="handleOperation('download', scope.row)">下载</span>
              <span class="btn" @click="handleOperation('modifyAndApply', scope.row)">修改重审</span>
              <!-- <span class="btn" @click="handleOperation('updatefConstractFile',scope.row)" v-if="scope.row.OpButton.UpdateFile">更新附件</span> -->
            </div>
            <div v-if="scope.row.Status === '已驳回'">
              <span class="btn" @click="handleOperation('viewPackage', scope.row)">查看套餐</span>
              <span class="btn" @click="handleOperation('rejectReason', scope.row)">驳回理由</span>
              <span class="btn" @click="handleOperation('applyRetrial', scope.row)">申请重审</span>
              <span class="btn" @click="handleOperation('delete', scope.row)" style="color: #ff0000">删除</span>
            </div>
            <div v-if="scope.row.Status === '已作废'">
              <span class="btn" @click="handleOperation('copy', scope.row)">复制模板</span>
              <span class="btn" @click="handleOperation('delete', scope.row)" style="color: #ff0000">删除</span>
            </div>
            <div v-if="scope.row.Status === '已签回'">
              <span class="btn" @click="handleOperation('checkBack', scope.row)">查看附件</span>
            </div>
            <div v-if="scope.row.Status === '已解约'">
              <span class="btn" @click="handleOperation('rescind', scope.row)">查看附件</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column key="admin操作" align="center" label="操作" width="150" v-if="RoleType === 'admin'">
          <template slot-scope="scope">
            <span class="btn" @click="handleOperation('viewPackage', scope.row)">查看套餐</span>
            <span class="btn" @click="handleOperation('download', scope.row)" v-if="scope.row.Status === '已审批'">下载</span>
            <span class="btn" @click="handleOperation('rejectReason', scope.row)" v-if="scope.row.Status === '已驳回'">驳回理由</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination layout="total,prev,pager,next,jumper" background :current-page="page" @current-change="handlePageChange" :page-size="pageSize" :total="total" class="pagination-wrap">
      </el-pagination>
    </div>

    <!-- 下载提示弹框 -->
    <el-dialog 
      v-dialogDrag 
      :append-to-body="true" 
      :visible.sync="showDownload" 
      width="50%" 
      center
    >
      <div slot="title">
        <img src="../../assets/img/icons/warn.png" alt="" width="16" height="16" style="vertical-align: middle" />
        <span style="vertical-align: middle">合同操作指南：</span>
      </div>
      <div class="download-popup-wrap">
        <!-- <img class="top-img" src="../../assets/img/constract/liucheng.png" alt="" /> -->
        <div class="top-img"></div>
        <!-- <a :href="item.Url+'?response-content-type=application/octet-stream'" :download="item.Title" v-for="item in contractTemList" :key="item.ContractTemplateId">{{ item.Title }}</a> -->
        <a @click="explainDialog">查看详细操作说明</a>
        <a @click="showlc=true" style="display:block;margin-top:10px;position:relative">查看详细操作流程图</a>
      </div>
    </el-dialog>

    <!-- 查看套餐弹框 -->
    <PreviewService :showPreview="showPreview" :serviceCon="serviceCon" @closePreviewService="handleClosePreviewService"></PreviewService>
  
    <!-- 查看合同列表弹框 -->
    <el-dialog 
      v-dialogDrag 
      :append-to-body="true" 
      :visible.sync="showPreContractList" 
      width="40%" 
      center
    >
      <div slot="title" style="font-size:15px">{{tabsActive==='业务合同'?'付款方列表':'代付方列表'}}</div>
      <ul class="precontract-list">
        <li 
          v-for="item in preContractList" 
          :key="ContractId+PaymentOnBehalfContractId"
          @click="handleGoContractdtl(tabsActive==='业务合同'?item.PaymentOnBehalfContractId:item.ContractId)"
        >{{item.CompanyName}}</li>
      </ul>
      <div style="text-align:center;margin:40px 0 30px 0">
        <el-button type="primary" style="width:200px" @click="showPreContractList=false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 选择新增合同类型 -->
    <el-dialog 
      v-dialogDrag 
      :append-to-body="true" 
      :visible.sync="showAddTypeDia" 
      width="800px" 
      class="self-dialog"
      center
    >
      <div style="text-align:center;margin:30px 0 100px 0">
        <img width="191" src="../../assets/img/constract/bzht.png" @click="$router.push('/addcontract')" style="margin-right:80px;cursor: pointer;">
				<img width="191" src="../../assets/img/constract/dfht.png" @click="$router.push('/addcontractdc')" style="cursor: pointer;">
        <p style="font-size:15px;color:#333;text-align:left;padding-left:100px;margin-top:30px">
					注：标准代付指的是无法签署三方协议和代付合同时，可以选择和代付方签署该类型合同
				</p>
      </div>
    </el-dialog>

    <!-- 销售更新合同文件 -->
    <el-dialog top="30vh" v-dialogDrag width="570px" :visible.sync="showUploadAttachment" :modal-append-to-body="false" @close="showUploadAttachment=false">
      <div slot="title">
        <img width='15' src="../../assets/img/icons/edit1.png" alt="">
        <span style="display:inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;max-width:450px">更新合同附件({{uploadFileData.CompanyName}})</span>
      </div>
      <div class="upload-attachment-wrap">
        <div style="display:flex;align-items: center;">
          <input type="file" name="file" @change="fileSelected" id="fileCard" style="display: none" />
          <div class="box"><span v-if="!uploadFileData.name" style="color:#999">请选择文件</span>{{uploadFileData.name}}</div>
          <!-- <el-button type="primary" @click="handleUploadAttachment">选择文件</el-button> -->
          <el-upload :before-upload="checkFileBeforeUpload">
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </div>
        <div style="text-align:center;margin:60px 0 30px 0">
          <el-button type="primary" @click="handleConfirmUpdateContractFile">确定</el-button>
          <el-button type="primary" plain @click="showUploadAttachment=false">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <explain-dlg  :explainShowDownload.sync="explainShowDownload"/>
    <el-dialog 
      v-dialogDrag 
      :append-to-body="true" 
      :visible.sync="showlc" 
      width="90vw" 
      top="5vh"
      class="self-dialog"
      center>
        <img style="width:100%" src="../../assets/img/constract/bg.png" alt="">
      </el-dialog>
  </div>
</template>

<script>
import PreviewService from "./components/PreviewService.vue";
import { contractInterface,customInterence } from "@/api/api.js";
import ExplainDlg from './components/explainDlg.vue';
export default {
  name: "constractList",
  components: {
    PreviewService,
    ExplainDlg,
  },
  computed: {
    exportExcel() {
      let baseUrl = process.env.API_ROOT + "/contract/list";
      let token = localStorage.getItem("auth") || "";
      let paramStr = "";
      let obj = {
        ContractType: this.constractTypeVal,
        ContractStatus: this.constractStatusVal,
        ProductId: this.constractBelongVal || 0,
        ModifyStartTime: !this.timeRange?'':this.timeRange[0] ? `${this.timeRange[0]} 00:00:00` : "",
        ModifyEndTime: !this.timeRange?'':this.timeRange[1] ? `${this.timeRange[1]} 23:59:59` : "",
        SellerId: '',
        Keyword: this.searchVal,
        KeywordType:this.searchType,
        IsExport:true,
        ContractBusinessType:this.tabsActive,
      };
      if(this.constractSellerVal.length){
        obj.SellerId=this.constractSellerVal.map(item=>{
					return item[item.length-1]
				}).join(',')
      }
      for (let key in obj) {
        paramStr = `${paramStr}&${key}=${obj[key]}`;
      }
      return `${baseUrl}?${token}${paramStr}`;
    },
  },
  //进入前是否清除参数
  beforeRouteEnter(to, from, next) {
    if(from.path!='/contractdetail'&&from.path!='/contractdetaildc'&&from.path!='/addcontractdc'){
      sessionStorage.removeItem('contractListBack')
      sessionStorage.removeItem('contractListTabs')
    }
    next()
  },
  //离开前缓存页面状态
  beforeRouteLeave(to, from, next) {
    let obj={
      page:this.page,
      searchVal:this.searchVal,
      searchType:this.searchType,
      timeRange:this.timeRange,
      constractTypeVal:this.constractTypeVal,
      constractStatusVal:this.constractStatusVal,
      constractBelongVal:this.constractBelongVal,
      constractSellerVal:this.constractSellerVal,
    }
    sessionStorage.setItem('contractListBack',JSON.stringify(obj))
    sessionStorage.setItem('contractListTabs',this.tabsActive)
    next()
  },
  data() {
    return {
      tabs:[
        {name:'业务合同'},
        {name:"代付合同"}
      ],
      tabsActive:sessionStorage.getItem('contractListTabs')||'业务合同',
      searchType:'使用方',
      showPreContractList:false,
      preContractList:[],
      showAddTypeDia:false,//新增合同类型弹窗

      RoleType: localStorage.getItem("Role") || "",
      contractTemList: [], //合同模板列表
      serviceCon: [], //套餐数据
      showPreview: false, //查看套餐弹窗
      showDownload: false, //下载合同模板弹窗
      page: 1,
      pageSize: 10,
      total: 0,
      searchVal: "", //搜索值
      timeRange: ["", ""], //选择时间段
      constractTypeOptions: [
        {
          value: "新签合同",
          label: "新签合同",
        },
        {
          value: "续约合同",
          label: "续约合同",
        },
        {
          value: "补充协议",
          label: "补充协议",
        },
      ], //合同类型选项
      constractTypeVal: "", //选择的合同类型值
      constractStatusOptions: [
        {
          value: "待提交",
          lable: "待提交",
        },
        {
          value: "待审批",
          lable: "待审批",
        },
        {
          value: "已撤回",
          lable: "已撤回",
        },
        {
          value: "已审批",
          lable: "已审批",
        },
        {
          value: "已驳回",
          lable: "已驳回",
        },
        {
          value: "已作废",
          lable: "已作废",
        },
        {
          value: "已签回",
          lable: "已签回",
        },
        {
          value: "已解约",
          lable: "已解约",
        },
      ], //合同状态选项
      constractStatusVal: "", //选择的合同状态值
      constractBelongOptions: [
        {
          value: "1",
          label: "FICC",
        },
        {
          value: "2",
          label: "权益",
        },
      ], //合同归属选项
      constractBelongVal: "", //合同归属值
      constractSellerOptions: [], //申请销售列表
      constractSellerVal: "", //申请销售值
      defaultSalesProps:{
				multiple: true,
				label:'RealName',
				children:'ChildrenList',
				value:'AdminId'
			},//销售级联配置
      tableList: [], //合同列表数据（表格）

      showUploadAttachment:false,//销售更新合同文件弹窗
      uploadFileData:{
        name:"",//文件名
        CompanyName:"",//客户名
        url:'',
        contractId:0,
        file:null,
      },//销售更新合同文件数据
      explainShowDownload:false,//操作详情
      showlc:false,
    };
  },
  created() {
    if(sessionStorage.getItem('contractListBack')){
      let cache=JSON.parse(sessionStorage.getItem('contractListBack'))
      this.page=cache.page
      this.searchVal=cache.searchVal
      this.timeRange=cache.timeRange
      this.constractBelongVal=cache.constractBelongVal
      this.constractTypeVal=cache.constractTypeVal
      this.constractStatusVal=cache.constractStatusVal
      this.constractSellerVal=cache.constractSellerVal
    }
    if(this.RoleType === 'admin'){
      this.constractStatusOptions= [
        {
          value: "待审批",
          lable: "待审批",
        },
        {
          value: "已审批",
          lable: "已审批",
        },
        {
          value: "已驳回",
          lable: "已驳回",
        },
        {
          value: "已作废",
          lable: "已作废",
        },
        {
          value: "已签回",
          lable: "已签回",
        },
        {
          value: "已解约",
          lable: "已解约",
        },
      ] //合同状态选项
    }
    this.getContractList();
    this.getSellerList();
  },
  methods: {

    // 业务合同、代付合同切换
    handleChangeTabs(e){
      this.tabsActive=e
      this.handleRefreshPage()
    },

    // 业务合同查看代付合同、代付合同查看
    handlePreviewContract(e){
      // 只有一个直接跳转
      if(e.length===1){
        let contractId=0
        if(this.tabsActive==='业务合同'){
          contractId=e[0].PaymentOnBehalfContractId
        }else if(this.tabsActive==='代付合同'){
          contractId=e[0].ContractId
        }
        this.handleGoContractdtl(contractId)
      }else if(e.length>1){
        this.preContractList=e
        this.showPreContractList=true
      }
      
    },

    // 跳转合同预览
    handleGoContractdtl(id){
      let {href} = this.$router.resolve({path:"/contractdtl",query:{contractid:id}});
			window.open(href,'_blank');
    },

    checkFileBeforeUpload(file){
      let hostfile = file;
      let size = Math.floor(hostfile.size / 1024 / 1024);
      if (size > 200) {
        this.$message.error("上传文件大小不能大于200M！");
        hostfile = {};
        return false;
      }
      if (hostfile.name.toLowerCase().includes(".pdf")||hostfile.name.toLowerCase().includes(".doc")||hostfile.name.toLowerCase().includes(".docx")) {
         this.uploadFileData.name=hostfile.name.toLowerCase()
          this.uploadFileData.file=hostfile
        } else {
          this.$message.error("请上传PDF/word文件！");
        }
      return false
    },

    // 销售更新合同附件
    handleUploadAttachment(){
      $("#fileCard").click();
    },

    // 选择文件上传
    fileSelected() {
      //选择文件上传
      if (document.getElementById("fileCard").files[0]) {
        let hostfile = document.getElementById("fileCard").files[0];
        let size = Math.floor(hostfile.size / 1024 / 1024);
        if (size > 200) {
          this.$message.error("上传文件大小不能大于200M！");
          hostfile = {};
          return false;
        }
        if (hostfile.name.toLowerCase().includes(".pdf")||hostfile.name.toLowerCase().includes(".doc")||hostfile.name.toLowerCase().includes(".docx")) {
          // let form = new FormData();
          // form.append("file", hostfile); //hostfile.name
          // customInterence.upload(form).then((res) => {
          //   if (res.Ret === 200) {
          //     // that.$message.success( '上传成功' );
          //     this.uploadFileData.url = res.Data.ResourceUrl;
          //     this.uploadFileData.name=hostfile.name.toLowerCase()
          //   }
          //   $("#fileCard").val("");
          //   hostfile = {};
          // });
          this.uploadFileData.name=hostfile.name.toLowerCase()
          this.uploadFileData.file=hostfile
        } else {
          this.$message.error("请上传PDF/word文件！");
        }
      }
    },

    // 确定更新合同附件
    async handleConfirmUpdateContractFile(){
      if(!this.uploadFileData.file){
        this.$message.warning('请上传文件');
        return
      }
      let form = new FormData();
      form.append("file", this.uploadFileData.file)
      form.append('ContractId',this.uploadFileData.contractId)
      // const res=await contractInterface.updateContractFile({
      //   ContractId:this.uploadFileData.contractId,
      //   FileUrl:this.uploadFileData.url
      // })
      const res=await contractInterface.updateContractFile(form)
      if(res.Ret===200){
        this.$message.success('更新成功')
        this.getContractList()
        this.showUploadAttachment=false
      }
    },

    //获取所属销售列表
    getSellerList() {
      contractInterface.getSellerList().then((res) => {
        if (res.Ret === 200) {
          this.constractSellerOptions = res.Data.List;
        }
      });
    },

    //下载合同模板
    handleDownloadContractTemplate() {
      contractInterface.getContractTemplate().then((res) => {
        if (res.Ret === 200) {
          this.contractTemList = res.Data;
          this.showDownload = true;
        }
      });
    },

    //刷新页面
    handleRefreshPage() {
      this.page = 1;
      this.searchVal = "";
      this.timeRange = ["", ""];
      this.constractTypeVal = "";
      this.constractStatusVal = "";
      this.constractBelongVal=''
      this.constractSellerVal=''
      this.getContractList();
    },

    //提交申请
    handleSubmitApproval(id) {
      contractInterface.applyContract({ ContractId: Number(id) }).then((res) => {
        if (res.Ret === 200) {
          this.$message.success("提交成功");
          this.handleRefreshPage();
        }
      });
    },

    //撤回申请
    handleCancelApplyContract(ContractApprovalRecordId, ContractId) {
      contractInterface.cancelApplyContract({ ContractApprovalRecordId, ContractId }).then((res) => {
        if (res.Ret === 200) {
          this.$message.success("撤回成功");
          this.handleRefreshPage();
        }
      });
    },

    /**
     * 操作
     * type 操作类型
     * e    数据
     * 查看套餐(viewPackage)、驳回理由(rejectReason)、申请重审(applyRetrial)
     * 删除(delete)、下载(download)、作废合同(cancelConstract)、撤回申请(backApply)
     * 修改合同(modifyConstract)、复制模板(copy)、编辑(edit)、提交审批(submitApproval)
     * 未提交审核的下载(downloadTem) 查看附件(已签回 checkBack  已解约rescind)  销售更新合同附件(updatefConstractFile)
     * 修改重审(modifyAndApply)
     */
    handleOperation:_.debounce(function(type, e) {
      if(type==='checkBack'){
        const url=e.CheckBackFileUrl
        if(!url){
          this.$message.warning('文件错误')
          return
        }
        const reg = /\.(pdf)$/;
        // pdf
        if(reg.test(url)){
          window.open(url,'_blank');
        }else{
          window.open('https://view.officeapps.live.com/op/view.aspx?src='+url,'_blank');
        }
        // window.open(e.CheckBackFileUrl,'_blank');
      }

      if(type==='rescind'){
        const url=e.RescindFileUrl
        if(!url){
          this.$message.warning('文件错误')
          return
        }
        const reg = /\.(pdf)$/;
        // pdf
        if(reg.test(url)){
          window.open(url,'_blank');
        }else{
          window.open('https://view.officeapps.live.com/op/view.aspx?src='+url,'_blank');
        }
        // window.open(e.RescindFileUrl,'_blank');
      }

      if (type === "submitApproval") {
        this.handleSubmitApproval(e.ContractId);
        return;
      }

      if (type === "delete") {
        this.$confirm("是否确认删除合同？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          contractInterface.contractDelete({ ContractId: e.ContractId }).then((res) => {
            if (res.Ret === 200) {
              this.$message.success("删除成功");
              this.handleRefreshPage();
            }
          });
        });
        return;
      }

      if (type === "edit") {
        if(e.ContractBusinessType==='业务合同'){
          this.$router.push({
            path: "/editcontract",
            query: {
              contractId: e.ContractId,
              type: type,
            },
          });
        }else{
          this.$router.push({
            path: "/editcontractdc",
            query: {
              contractId: e.ContractId,
              type: type,
            },
          });
        }
        
        return;
      }

      if (type === "viewPackage") {
        if(e.ContractBusinessType==='业务合同'){
          this.serviceCon = e.Service;
        }else{
          let arr=[]
          e.RelationContractList.forEach(item=>{
            item.Service.forEach(item2=>{
              arr.push(item2)
            })
          })
          this.serviceCon=arr
        }
        
        this.showPreview = true;
        return;
      }

      if (type === "rejectReason") {
        this.$alert(e.ApprovalRemark, "驳回理由", {
          confirmButtonText: "知道了",
          showCancelButton: false,
        }).then(() => {});
        return;
      }

      if (type === "cancelConstract") {
        this.$confirm("作废后合同将不能再使用，是否确认作废合同？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          contractInterface.contractInvalid({ ContractId: e.ContractId }).then((res) => {
            if (res.Ret === 200) {
              this.$message.success("作废成功");
              this.handleRefreshPage();
            }
          });
        });
        return;
      }

      if (type === "backApply") {
        this.$confirm("确认撤回该合同吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.handleCancelApplyContract(e.ContractApprovalRecordId, e.ContractId);
        });
        return;
      }

      if (type === "download") {
        let link = document.createElement("a");
        link.href = e.FileUrl + "?response-content-type=application/octet-stream";
        link.setAttribute("download", e.ContractCode);
        link.style.display = "none"; //a标签隐藏
        document.body.appendChild(link);
        link.click();
        return;
      }

      if(type==='downloadTem'){
        let baseUrl = process.env.API_ROOT + "/contract/downLoad/tmpContract";
        let token = localStorage.getItem("auth") || "";
        let path=`${baseUrl}?${token}&ContractId=${e.ContractId}`
        let link = document.createElement("a");
        link.href = path;
        link.setAttribute("download", e.ContractCode);
        link.style.display = "none"; //a标签隐藏
        document.body.appendChild(link);
        link.click();
        return
      }

      if (type === "modifyConstract") {
        if(e.ContractBusinessType==='业务合同'){
          this.$router.push({
            path: "/editcontract",
            query: {
              contractId: e.ContractId,
              type: type,
            },
          });
        }else{
          this.$router.push({
            path: "/editcontractdc",
            query: {
              contractId: e.ContractId,
              type: type,
            },
          });
        }
        
        return;
      }

      if (type === "applyRetrial") {
        if(e.ContractBusinessType==='业务合同'){
          this.$router.push({
            path: "/retrialcontract",
            query: {
              contractId: e.ContractId,
              type: type,
            },
          });
        }else{
          this.$router.push({
            path: "/retrialcontractdc",
            query: {
              contractId: e.ContractId,
              type: type,
            },
          });
        }
        
        return;
      }

      if (type === "copy") {
        if(e.ContractBusinessType==='业务合同'){
          this.$router.push({
            path: "/copycontract",
            query: {
              contractId: e.ContractId,
              type: type,
            },
          });
        }else{
          this.$router.push({
            path: "/copycontract",
            query: {
              contractId: e.ContractId,
              type: type,
            },
          });this.$router.push({
            path: "/copycontractdc",
            query: {
              contractId: e.ContractId,
              type: type,
            },
          });
        }
        
        return;
      } 

      // 销售更新合同附件
      if(type==='updatefConstractFile'){
        let fileName=e.FileUrl.substring(e.FileUrl.lastIndexOf('/') + 1)
        this.uploadFileData.name=fileName
        this.uploadFileData.CompanyName=e.CompanyName
        this.uploadFileData.contractId=e.ContractId
        this.uploadFileData.url=e.FileUrl
        this.showUploadAttachment=true
      }

      // 修改重审
      if(type==='modifyAndApply'){
        if(e.ContractBusinessType==='业务合同'){
          this.$router.push({
            path: "/modifyapply",
            query: {
              contractId: e.ContractId,
              type: type,
            },
          });
        }else{
          this.$router.push({
            path: "/modifyapplydc",
            query: {
              contractId: e.ContractId,
              type: type,
            },
          });
        }

        return
      }


    },200),

    //关闭查看套餐弹窗
    handleClosePreviewService() {
      this.showPreview = false;
    },

    // 获取列表数据
    getContractList() {
      // 处理销售筛选
			let salesArr=[]
			if(this.constractSellerVal.length){
				salesArr=this.constractSellerVal.map(item=>{
					return item[item.length-1]
				})
			}
      let params = {
        ContractType: this.constractTypeVal,
        ContractStatus: this.constractStatusVal,
        ProductId: Number(this.constractBelongVal),
        ModifyStartTime: !this.timeRange?'':this.timeRange[0] ? `${this.timeRange[0]} 00:00:00` : "",
        ModifyEndTime: !this.timeRange?'':this.timeRange[1] ? `${this.timeRange[1]} 23:59:59` : "",
        SellerId: salesArr.join(','),
        Keyword: this.searchVal,
        KeywordType:this.searchType,
        CurrentIndex: this.page,
        PageSize: this.pageSize,
        ContractBusinessType:this.tabsActive,
      };
      contractInterface.getContractList(params).then((res) => {
        if (res.Ret === 200) {
          this.tableList = res.Data.List;
          this.total = res.Data.Paging.Totals;
        }
      });
    },

    //类型或者状态变更
    handleSelectChange() {
      this.searchVal = "";
      this.page = 1;
      this.getContractList();
    },

    //页码改变
    handlePageChange(e) {
      this.page = e;
      this.getContractList();
    },

    //跳转合同详情
    handleGoDetail(type,id) {
      if(type==='业务合同'){
        this.$router.push({ path: "/contractdetail", query: { contractId: id } });
      }else{
        this.$router.push({ path: "/contractdetaildc", query: { contractId: id } });
      }
    },

    //搜索
    handleSearch() {
      this.timeRange = ["", ""];
      this.constractTypeVal = "";
      this.constractStatusVal = "";
      this.constractSellerVal=''
      this.constractBelongVal=''
      this.page = 1;
      this.getContractList();
    },
    //查看详细操作说明
    explainDialog(){
      this.explainShowDownload=true;
    }
  },
};
</script>


<style lang="scss">
.el-message-box__header .el-message-box__title {
  color: #333 !important;
}
.el-date-table td.start-date div::after {
  content: "起";
  display: block;
  position: absolute;
  top: 64%;
  left: 50%;
  transform: translateX(-50%) scale(0.9);
  color: #666;
  z-index: 1000;
  font-size: 10px;
}
.el-date-table td.end-date div::after {
  content: "终";
  display: block;
  position: absolute;
  top: 64%;
  left: 50%;
  transform: translateX(-50%) scale(0.9);
  color: #666;
  z-index: 1000;
  font-size: 10px;
}
.el-table__empty-block{
  min-height: 300px;
}

.container-explain .el-dialog__header {
    background-color: #fff !important;
}

.self-dialog{
		width: 100% !important;
		max-width: 100% !important;
		.el-dialog__header{
			background-color: #fff;
			.el-dialog__close.el-icon.el-icon-close{
				color: #666;
			}
		}
	}
</style>

<style lang="scss" scoped>
.precontract-list{
  border: 1px solid #DCDFE6;
  li{
    font-size: 14px;
    color: #409eff;
    cursor: pointer;
    padding: 14px 20px;
    border-bottom: 1px solid #DCDFE6;
  }
  li:last-child{
    border: none;
  }
}

.upload-attachment-wrap{
  .box{
    width: 380px;
    display: inline-block;
    box-sizing: border-box;
    height: 40px;
    line-height: 40px;
    padding: 0 17px;
    font-size: 14px;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    margin-right: 20px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.top-wrap {
  margin-bottom: 28px;
  padding: 20px 30px;
  // min-height: 50px;
  background: #fff;
  border: 1px solid #ececec;
  border-radius: 4px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
}

.tabs-wrap{
  display: flex;
  margin-bottom: 20px;
  align-items: center;
  .tab {
    padding-bottom: 5px;
		text-align: center;
		font-size: 14px;
		cursor: pointer;
		transition-delay: 0.05s;
    margin-right: 40px;
    color: #333;
		&:hover {
			color: #409EFF;
		}
		&.act {
      color: #409eff;
			border-bottom: 2px solid #409EFF;
		}
	}
}

.list-wrap {
  min-height: calc(100vh - 390px);
  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);
  .constract-sn {
    cursor: pointer;
    color: #409eff;
  }
  .btn {
    font-size: 14px;
    display: inline-block;
    color: #409eff;
    cursor: pointer;
    margin: 0 3px;
  }
  .pagination-wrap {
    position: absolute;
    bottom: 24px;
    right: 30px;
  }
}

.download-popup-wrap {
  text-align: center;
  padding-bottom: 80px;
  .top-img {
    // width: 80%;
    // display: block;
    // margin: 20px auto;
    width: 100%;
    padding-bottom: 53%;
    background-image: url('../../assets/img/constract/liucheng.png');
    background-size: cover;
    background-position: center;
  }
  a {
    color: #409eff;
    cursor: pointer;
    // &::before {
    //   content: "";
    //   display: inline-block;
    //   width: 15px;
    //   height: 15px;
    //   background-image: url("../../assets/img/constract/download.png");
    //   background-size: cover;
    //   margin-right: 10px;
    // }
  }
}

</style>
