<template>
  <div class="contractlist-container">
    <div class="top-wrap">
      <a :href="exportExcel" download>
        <el-button type="primary">下载EXCEL</el-button>
      </a>
      <el-button type="primary" plain @click="handleDownloadContractTemplate" style="margin-left:10px">合同操作指南</el-button>
      <el-input placeholder="合同编号/客户名称/社会信用码" v-model="searchVal" style="max-width: 520px; float: right" @input="handleSearch" clearable>
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
    </div>
    <div class="list-wrap">
      <div style="margin-top: 10px; margin-bottom: 10px">
        <el-select 
          v-model="constractTypeVal" 
          @change="handleSelectChange" 
          placeholder="合同类型" 
          clearable 
          style="margin-bottom: 20px;margin-right:20px;width:150px"
        >
          <el-option v-for="item in constractTypeOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <el-select 
          v-model="constractStatusVal" 
          @change="handleSelectChange" 
          placeholder="合同状态" 
          style="margin-bottom: 20px;margin-right:20px;width:150px"
        >
          <el-option v-for="item in constractStatusOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <!-- <el-select v-model="seller" @change="handleSelectChange" placeholder="申请销售" clearable style="margin-bottom: 20px;margin-right:20px">
          <el-option v-for="item in sellerList" :key="item.AdminId" :label="item.RealName" :value="item.AdminId"> </el-option>
        </el-select> -->
        <el-cascader
            v-model="seller"
            placeholder="申请销售"
            style="min-width:250px;margin-bottom: 20px;margin-right:20px"
            :options="sellerList"
            :props="defaultSalesProps"
            :show-all-levels="false"
            collapse-tags
            clearable
            filterable
            @change="handleSelectChange">
        </el-cascader>
        <div style="display:inline-block">
          <span>是否代付</span>
          <el-select
            v-model="ContractBusinessType"
            @change="handleSelectChange" 
            placeholder="是否代付" 
            style="margin-bottom: 20px;margin-right:20px;width:150px"
          >
            <el-option label="全部" value=""></el-option>
            <el-option label="否" value="业务合同"></el-option>
            <el-option label="是" value="代付合同"></el-option>
          </el-select>
        </div>
        <block v-if="RoleType === 'compliance'">
          <el-select 
            clearable 
            v-model="constractBelongVal" 
            @change="handleSelectChange" 
            placeholder="合同归属" 
            style="margin-bottom: 20px;margin-right:20px;width:150px"
          >
            <el-option v-for="item in constractBelongOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
          <el-date-picker 
            style="margin-bottom: 20px;margin-right:20px;width:300px" 
            v-model="timeRange" 
            type="daterange" 
            @change="handleSelectChange" 
            value-format="yyyy-MM-dd" 
            range-separator="至" 
            start-placeholder="开始日期" 
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </block>
      </div>
      <el-table :data="tableList" border>
        <el-table-column align="center" prop="ContractCode" label="合同编号" width="160">
          <template slot-scope="scope">
            <span class="constract-sn" @click="handleGoDetail(scope.row.ContractId,scope.row.ContractInfo.ContractBusinessType)">{{ scope.row.ContractCode }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="ContractType" label="合同类型" width="80">
          <template slot-scope="scope">
            {{scope.row.ContractInfo.ContractBusinessType==='代付合同'?'代付合同':scope.row.ContractType}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="合同有效期" width="180">
          <template slot-scope="scope">{{ scope.row.StartDateStr|formatTime }}~{{ scope.row.EndDateStr|formatTime }}</template>
        </el-table-column>
        <el-table-column align="center" prop="Price" label="合同金额" width="80">
          <template slot-scope="scope">{{ scope.row.Price|formatPriceHasPoint }}</template>
        </el-table-column>
        <el-table-column align="center" prop="CompanyName" label="客户名称" ></el-table-column>
        <el-table-column align="center" prop="CreateTimeStr" label="提交审批时间" width="160" :formatter="formatter"></el-table-column>
        <el-table-column align="center"  label="审批时间" width="160" v-if="constractStatusVal!=='待审批'">
          <template slot-scope="scope">
            <span v-if="scope.row.Status === '待审批'">- -</span>
            <span v-else>{{scope.row.ApproveTimeStr}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="ApplyContent" label="待审内容"></el-table-column>
        <el-table-column align="center" prop="SellerName" label="申请人" width="80"></el-table-column>
        <el-table-column 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 align="center" label="操作">
          <template slot-scope="scope">
            <div v-if="scope.row.Status === '待审批'">
              <span class="btn" @click="handleShowApproval(scope.row)" v-if="scope.row.OpButton.Approval">审批</span>
              <span v-else>- -</span>
            </div>
            <div v-else-if="scope.row.Status === '已审批'">
              <span class="btn" @click="handleShowApproval(scope.row)">审批详情</span>  
              <span class="btn" @click="handleDownloadContract(scope.row)">下载</span>
              <span class="btn" @click="handleShowUploadAttachment(scope.row,1)" v-if="scope.row.OpButton.CheckBackFile">上传附件</span>
            </div>
            <div v-else-if="scope.row.Status === '已作废'">
              <span class="btn" @click="handleShowService(scope.row)">查看套餐</span>
            </div>
            <div v-else-if="scope.row.Status === '已签回'">
              <span class="btn" @click="handleShowUploadAttachment(scope.row,2)" v-if="scope.row.OpButton.CheckBackFile">更新附件</span>
              <span class="btn" @click="handleViewFile(scope.row.CheckBackFileUrl)">查看附件</span>
              <span class="btn" @click="handleShowUploadAttachment(scope.row,3)" v-if="scope.row.OpButton.RescindFile">解除合同</span>
            </div>
            <div v-else-if="scope.row.Status === '已解约'">
              <span class="btn" @click="handleViewFile(scope.row.RescindFileUrl)">查看附件</span>
            </div>
            <div v-else>
              <span class="btn" @click="handleShowApproval(scope.row)">审批详情</span>
              <!-- <span class="btn" v-if="scope.row.Status === '已审批'" @click="handleDownloadContract(scope.row)">下载</span> -->
            </div>
          </template>
        </el-table-column>

        <div slot="empty" style="padding:100px 0">暂无数据</div>
      </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 width="58%" top="5vh" v-dialogDrag :visible.sync="show" :modal-append-to-body="false" @close="handleClose">
      <div slot="title" v-if="approvalData">
        <span>合同编号： {{ approvalData.ContractInfo.ContractCode }}</span>
      </div>
      <div class="approval-wrap" v-if="approvalData">
        <div class="main">
          <!-- 代付合同 -->
          <table class="table-wrap" v-if="approvalData.ContractInfo.ContractBusinessType==='代付合同'">
            <tbody>
              <tr>
                <td class="table-item width-50">代付方：{{ approvalData.ContractInfo.CompanyName }}</td>
                <td class="table-item width-50">社会信用码：{{ approvalData.ContractInfo.CreditCode }}</td>
              </tr>
              <tr>
                <td class="table-item width-50">公司地址：{{ approvalData.ContractInfo.Province }}{{ approvalData.ContractInfo.City }}{{ approvalData.ContractInfo.Address }}</td>
                <td class="table-item width-50">申请销售：{{ approvalData.ContractInfo.SellerName }}</td>
              </tr>
              <tr>
                <td class="table-item width-50">代付金额：{{ approvalData.ContractInfo.Price|formatPriceHasPoint }}元</td>
                <td class="table-item width-50">合同归属：{{ approvalData.ContractInfo.ProductId === 1 ? "FICC" : "权益" }}</td>
              </tr>
              <tr>
                <td class="table-item width-50">实际使用方：{{ approvalData.ContractInfo.RelationContractDetailList[0].CompanyName }}</td>
                <td class="table-item width-50">合同金额：{{ approvalData.ContractInfo.RelationContractDetailList[0].Price|formatPriceHasPoint }}元</td>
              </tr>
              <tr>
                <td class="table-item" colspan="2">合同期限：{{ approvalData.ContractInfo.StartDateStr|formatTime }}~{{ approvalData.ContractInfo.EndDateStr|formatTime }}（{{ approvalData.ContractInfo.StartDate | formateYear(approvalData.ContractInfo.EndDate) }}）</td>
              </tr>
            </tbody>
          </table>
          <!-- 业务合同 -->
          <block v-else>
          <table class="table-wrap" >
            <tbody>
              <tr>
                <td class="table-item width-50">客户名称：{{ approvalData.ContractInfo.CompanyName }}</td>
                <td class="table-item width-50">社会信用码：{{ approvalData.ContractInfo.CreditCode }}</td>
              </tr>
              <tr>
                <td class="table-item width-50">公司地址：{{ approvalData.ContractInfo.Province }}{{ approvalData.ContractInfo.City }}{{ approvalData.ContractInfo.Address }}</td>
                <td class="table-item width-50">申请销售：{{ approvalData.ContractInfo.SellerName }}</td>
              </tr>
              <tr>
                <td class="table-item width-50">合同类型：{{ approvalData.ContractInfo.ContractType }}</td>
                <td class="table-item width-50">合同金额：{{ approvalData.ContractInfo.Price|formatPriceHasPoint }}元</td>
              </tr>
              <tr>
                <td class="table-item width-50">
                  合同期限：{{ approvalData.ContractInfo.StartDateStr|formatTime }}~{{ approvalData.ContractInfo.EndDateStr|formatTime }}（{{ approvalData.ContractInfo.StartDate | formateYear(approvalData.ContractInfo.EndDate) }}）
                </td>
                <td class="table-item width-50">合同归属：{{ approvalData.ContractInfo.ProductId === 1 ? "FICC" : "权益" }}</td>
              </tr>
              <tr>
                <td class="table-item" colspan="2" style="text-align: left">付款方：{{ approvalData.ContractInfo.PayChannel||approvalData.ContractInfo.CompanyName }}</td>
              </tr>
              <tr>
                <td class="table-item" colspan="2" style="text-align: left">付款方式说明：{{ approvalData.ContractInfo.PayRemark }}</td>
              </tr>
            </tbody>
          </table>
          </block>
          <table class="table-wrap" style="border-top: 0">
            <tbody>
              <tr v-if="change.first">
                <td class="table-item" :rowspan="change.list.length + 1" style="width: 100px">变更说明</td>
                <td class="table-item" style="text-align: left">1. 
                  <div v-html="formatChangeInfo(change.first)" style="padding-left:14px;margin-top:-19px"></div>
                </td>
              </tr>
              <tr v-for="(item,index) in change.list" :key="item">
                <td class="table-item" style="text-align: left">{{index+2}}.
                  <div v-html="formatChangeInfo(item)" style="padding-left:14px;margin-top:-19px"></div>
                </td>
              </tr>
              <tr>
                <td class="table-item" colspan="2" style="text-align: left">销售备注：{{approvalData.ContractInfo.SellerRemark||'无'}}</td>
              </tr>
            </tbody>
          </table>
          <!-- 服务内容 -->
          <div class="service-wrap">
            <h2 style="font-size: 14px;flex-shrink: 0;">服务内容：</h2>
            <div style="color: #666">
              <div style="margin-bottom: 10px" v-for="item in approvalData.ContractInfo.Service" :key="item.ServiceTemplateId">
                <span style="display: inline-block; width: 100px">{{ item.Title }}</span>
                <span style="display: inline-block; color: #1989fa; cursor: pointer" @click="handlePreviewService(item)">查看服务单</span>
              </div>
              <!-- div.package_varieties -->
              <div class="service_varieties" v-show="PermissionLookList && PermissionLookList.length!=0">
                <span>小套餐包含品种：</span>
                <el-form :model="PermissionLookList" id="service_varieties_form">
                  <el-form-item :label="item.ClassifyName+'：'" v-for="item in PermissionLookList" :key="item" label-width="124px" style="margin-bottom: 0;">
                    <span v-for="it in item.Items" :key="it.ChartPermissionId">{{it.PermissionName}}</span>
                  </el-form-item>
                </el-form>
              </div>
              <div style="margin-top: 16px;display:flex">
                <span style="display: inline-block;flex-shrink: 0;">补充内容：</span>
                <span style="display: inline-block">{{ approvalData.ContractInfo.Remark || "无" }}</span>
              </div>
            </div>
          </div>
          <div class="dashed-line"></div>
          <el-form ref="form" :model="form" :rules="formRule" label-width="100px" label-position="left" v-if="approvalData.Status==='待审批'">
            <el-form-item prop="status" label="审批状态">
              <el-radio-group v-model="form.status" @change="approvalFromStatusChange">
                <el-radio label="通过"></el-radio>
                <el-radio label="驳回"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item prop="reason" label="驳回理由" v-if="form.status === '驳回'">
              <el-input v-model="form.reason" placeholder="请输入理由" type="textarea"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="right">
          <el-button type="primary" style="width: 100%" @click="handlePreviewContract">预览合同</el-button>
          <div class="timeline-wrap">
            <el-timeline>
              <el-timeline-item color="#409EFF" v-for="item in operationList" :key="item.Id" placement="top" :timestamp="item.CreateTimeStr"> {{ item.OpUserName }}{{ item.Remark }} </el-timeline-item>
            </el-timeline>
          </div>
        </div>
      </div>
      <div style="text-align: center; margin-bottom: 40px; margin-top: 40px" v-if="approvalData">
        <block v-if="approvalData.Status==='待审批'">
          <el-button type="primary" style="margin-right: 24px" @click="handleConfirmApproval">确定</el-button>
          <el-button type="primary" plain @click="handleCancelApproval">取消</el-button>
        </block>
        <block v-else><el-button type="primary" @click="show=false">知道了</el-button></block>
      </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="" v-if="fileData.title==='更新签回合同'">
        <img width="15" src="../../assets/img/icons/up.png" alt="" v-else>
        <span style="display:inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;max-width:450px">{{fileData.title}}</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="!fileData.name" style="color:#999">请选择文件</span>{{fileData.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="handleConfirmAttachment">确定</el-button>
          <el-button type="primary" plain @click="showUploadAttachment=false">取消</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 查看套餐弹框 -->
    <PreviewService :showPreview="showService" :serviceCon="serviceCon" @closePreviewService="handleClosePreviewService"></PreviewService>
  
    <!-- 下载提示弹框 -->
    <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>

    <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 {CalculationDate} from '@/utils/CalculationDate'
import ExplainDlg from './components/explainDlg.vue';
export default {
  name: "approvalList",
  components: {
    PreviewService,
    ExplainDlg
  },
  computed:{
    exportExcel(){
      let baseUrl=process.env.API_ROOT+'/contract/approval/list'
      let token=localStorage.getItem('auth')||''
      let paramStr=''
      let obj={
        ContractType:this.constractTypeVal,
        Status:this.constractStatusVal=='全部'?'':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:this.seller,
        Keyword:this.searchVal,
        IsExport:true,
        ContractBusinessType:this.ContractBusinessType,
      }
      for(let key in obj){
        paramStr=`${paramStr}&${key}=${obj[key]}`
      }
      return `${baseUrl}?${token}${paramStr}`
    }
  },
  filters: {
    //计算多少年
    formateYear(s, e) {
      if (s) {
        return `有效期为${CalculationDate(s,e)}`
      } else {
        return "";
      }
    },
  },
  watch:{
    showUploadAttachment(nval,oval){
      if(!nval){
        this.fileData={
          type:0,
          title:"",
          name:"",
          url:'',
          file:null,
          contractId:0,
        }
      }
    }
  },
  //进入前是否清除参数
  beforeRouteEnter(to, from, next) {
    if(from.path!='/contractdetailapr'&&from.path!='/contractdetaildcapr'){
      sessionStorage.removeItem('contractAprListBack')
    }
    next()
  },
  //离开前缓存页面状态
  beforeRouteLeave(to, from, next) {
    let obj={
      page:this.page,
      searchVal:this.searchVal,
      constractTypeVal:this.constractTypeVal,
      constractStatusVal:this.constractStatusVal,
      seller:this.seller,
      constractBelongVal:this.constractBelongVal,
      timeRange:this.timeRange,
      ContractBusinessType:this.ContractBusinessType
    }
    sessionStorage.setItem('contractAprListBack',JSON.stringify(obj))
    next()
  },
  data() {
    return {
      ContractBusinessType:'',//合同业务类型，枚举值：’业务合同’,’代付合同’,不传默认是全部
      showUploadAttachment:false,//显示上传（更新附件）
      fileData:{
        type:0,//1 上传附件 2 更新附件 3 解除协议
        title:"",
        name:"",
        url:'',
        file:null,
        contractId:0,
      },//上传/更新附件文件数据

      RoleType: localStorage.getItem("Role") || "",
      change: {
        first:'',
        list:[]
      },//合同变更说明数据

      form: {
        status: "通过",
        reason: "",
      },
      formRule: {
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
        reason: [{ required: true, message: "请填写驳回理由", trigger: "blur" }],
      },

      showService: false, //显示套餐弹窗
      serviceCon:[],

      show: false, //显示审批弹窗
      operationList: [], //操作记录

      page: 1,
      pageSize: 10,
      total: 0,
      tableList: [],
      approvalData: null, //点击审批时弹窗中要用的数据
      operationList: [], //操作记录列表

      searchVal: "", //搜索值
      constractTypeOptions: [
        {
          value: "新签合同",
          label: "新签合同",
        },
        {
          value: "续约合同",
          label: "续约合同",
        },
        {
          value: "补充协议",
          label: "补充协议",
        },
        {
          value: "打分派点",
          label: "打分派点",
        },
      ], //合同类型选项
      constractTypeVal: "", //选择的合同类型值
      constractStatusOptions: [
        {
          value: "全部",
          lable: "全部",
        },
        {
          value: "待审批",
          lable: "待审批",
        },
        {
          value: "已审批",
          lable: "已审批",
        },
        {
          value: "已作废",
          lable: "已作废",
        },
        {
          value: "已签回",
          lable: "已签回",
        },
        {
          value: "已解约",
          lable: "已解约",
        }
      ], //合同状态选项
      constractStatusVal: "待审批", //选择的合同状态值
      sellerList: [], //申请销售列表
      seller: "", //选择的申请销售
      defaultSalesProps:{
				multiple: true,
				label:'RealName',
				children:'ChildrenList',
				value:'AdminId'
			},//销售级联配置
      constractBelongOptions: [
        {
          value: "1",
          label: "FICC",
        },
        {
          value: "2",
          label: "权益",
        },
      ], //合同归属选项
      constractBelongVal: "", //合同归属值
      timeRange: ["", ""], //选择时间段

      contractTemList: [], //合同模板列表
      showDownload: false, //下载合同模板弹窗
      explainShowDownload:false,//操作详情
      showlc:false,
      PermissionLookList:[] // 小套餐品种
    };
  },
  
  created() {
    //判断是否有缓存数据
    if(sessionStorage.getItem('contractAprListBack')){
      let cache=JSON.parse(sessionStorage.getItem('contractAprListBack'))
      this.page=cache.page
      this.searchVal=cache.searchVal
      this.constractTypeVal=cache.constractTypeVal
      this.constractStatusVal=cache.constractStatusVal
      this.seller=cache.seller
      this.ContractBusinessType=cache.ContractBusinessType
    }
    this.getSellerList();
    this.getApprovalList();
  },
  methods: {
    // 查看回签、解约附件
    handleViewFile(url){
      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');
      }
    },

    handleConfirmAttachment(){
      if(!this.fileData.file){
        this.$message.warning('请上传文件');
        return
      }
      if(this.fileData.type===1||this.fileData.type===2){
        this.handleCheckFile()
      }else if(this.fileData.type===3){
        this.handleRescindFile()
      }
    },

    //处理回签附件
    async handleCheckFile(){
      // const res=await contractInterface.uploadCheckFile({
      //   ContractId:Number(this.fileData.contractId),
      //   FileUrl:this.fileData.url
      // })
      let form = new FormData();
      form.append("file", this.fileData.file)
      form.append('ContractId',this.fileData.contractId)
      const res=await contractInterface.uploadCheckFile(form)
      if(res.Ret===200){
        if(this.fileData.type===1){
          this.$message.success('上传成功');
        }else{
          this.$message.success('更新成功');
        }
        
        this.getApprovalList()
        this.showUploadAttachment=false
      }
    },

    //处理解除协议
    async handleRescindFile(){
      // const res=await contractInterface.uploadRescindFile({
      //   ContractId:Number(this.fileData.contractId),
      //   FileUrl:this.fileData.url
      // })
      let form = new FormData();
      form.append("file", this.fileData.file)
      form.append('ContractId',this.fileData.contractId)
      const res=await contractInterface.uploadRescindFile(form)
      if(res.Ret===200){
        this.$message.success('解除成功');
        this.getApprovalList()
        this.showUploadAttachment=false
      }
    },

    // 显示上传附件弹窗 e 数据  type:1上传 2 更新 3解除
    handleShowUploadAttachment(e,type){
      if(type===1){
        this.fileData.title=`上传签回合同(${e.CompanyName})`
      }else if(type===2){
        this.fileData.title=`更新签回合同(${e.CompanyName})`
        this.fileData.name=e.CheckBackFileUrl.substring(e.CheckBackFileUrl.lastIndexOf('/') + 1)
        this.fileData.url=e.CheckBackFileUrl
      }else if(type===3){
        this.fileData.title=`上传解除协议(${e.CompanyName})`
      }
      this.fileData.contractId=e.ContractId
      this.fileData.type=type
      this.showUploadAttachment=true
    },

    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.fileData.file=hostfile
          this.fileData.name=hostfile.name.toLowerCase()
        } else {
          this.$message.error("请上传PDF/word文件！");
        }
      return false
    },

    // 上传（更新）附件
    handleUploadAttachment(){
      $("#fileCard").click();
    },

    // 选择文件上传
    fileSelected() {
      //选择文件上传
      console.log('aaa');
      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.fileData.url = res.Data.ResourceUrl;
          //     this.fileData.name=hostfile.name.toLowerCase()
          //   }
          //   $("#fileCard").val("");
          //   hostfile = {};
          // });
          this.fileData.file=hostfile
          this.fileData.name=hostfile.name.toLowerCase()
        } else {
          this.$message.error("请上传PDF/word文件！");
        }
      }
    },

    //下载合同
    handleDownloadContract(e){
      if(!e.FileUrl){
        this.$message.warning('合同文件正在后台生成中,请稍后刷新页面下载!')
        return
      }
      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();
    },
    
    //预览合同
    handlePreviewContract(){
      let {href} = this.$router.resolve({path:"/contractdtl",query:{contractid:this.approvalData.ContractId}});
			window.open(href,'_blank');
    },

    //跳转合同详情
    handleGoDetail(id,type) {
      if(type==='代付合同'){
        this.$router.push({ path: "/contractdetaildcapr", query: { contractId: id } });
      }else{
        this.$router.push({ path: "/contractdetailapr", query: { contractId: id } });
      }
      
    },

    //关闭预览套餐弹窗
    handleClosePreviewService(){
      this.showService=false
    },

    //预览套餐(审批弹框中)
    handlePreviewService(e) {
      this.serviceCon=[e]
      this.showService=true
    },

    handleShowService(e){
      this.serviceCon=e.ContractInfo.Service
      this.showService=true
    },

    //搜索
    handleSearch() {
      this.constractTypeVal = "";
      this.constractStatusVal = "全部";
      this.seller=''
      this.constractBelongVal=''
      this.timeRange=['','']
      this.ContractBusinessType=''
      this.page = 1;
      this.getApprovalList();
    },

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

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

    //获取审批列表
    getApprovalList() {
      let salesArr=[]
			if(this.seller.length){
				salesArr=this.seller.map(item=>{
					return item[item.length-1]
				})
			}
      let params = {
        ContractType: this.constractTypeVal,
        Status: this.constractStatusVal==='全部'?'':this.constractStatusVal,
        ProductId: Number(this.constractBelongVal),
        SellerId: salesArr.join(','),
        ModifyStartTime: !this.timeRange?'':this.timeRange[0] ? `${this.timeRange[0]} 00:00:00` : "",
        ModifyEndTime: !this.timeRange?'':this.timeRange[1] ? `${this.timeRange[1]} 23:59:59` : "",
        Keyword: this.searchVal,
        CurrentIndex: this.page,
        PageSize: this.pageSize,
        ContractBusinessType:this.ContractBusinessType,
      };
      contractInterface.getApprovalList(params).then((res) => {
        if (res.Ret === 200) {
          this.tableList = res.Data.List;
          this.total = res.Data.Paging.Totals;
        }
      });
    },

    //获取合同操作记录
    getContractOperationList(id) {
      contractInterface.getContractOperationList({ ContractId: id }).then((res) => {
        if (res.Ret === 200) {
          this.operationList = res.Data.List&&res.Data.List.map(item=>{
            return {...item,CreateTimeStr:item.CreateTimeStr.replace(/-/g,'.')}
          })||[];
        }
      });
    },

    //点击审批
    handleShowApproval(e) {
      this.approvalData = e;
      contractInterface.getContractDetail({ ContractId: e.ContractId }).then(({Data:{PermissionLookList,Service,RelationContractDetailList}})=>{
        // 获取小套餐的品种
        this.PermissionLookList = PermissionLookList
        // 获取权益服务内容
        this.approvalData.ContractInfo.Service = Service
        if(e.ContractInfo.ContractBusinessType==='代付合同'){
          let arr=[]
          RelationContractDetailList.forEach(item=>{
            item.Service.forEach(item2=>{
              arr.push(item2)
            })
          })
          this.approvalData.ContractInfo.Service=arr
        }
        this.show = true
      })

      // 处理变更数据
      let temarr=e.ContractInfo.ModifyContent.split('<br/>').filter(item=> item)
      // console.log(temarr);
      this.change.first=temarr[0]
      this.change.list=temarr.slice(1)

      // console.log(temarr);
      this.getContractOperationList(e.ContractId);
    },

    //刷新列表
    handleRefreshList(){
      this.searchVal=''
      this.constractTypeVal=''
      this.constractStatusVal='待审批'
      this.seller=''
      this.page=1
      this.getApprovalList()
    },

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

    //提交审批
    handleConfirmApproval() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 通过
          if (this.form.status === "通过") {
            contractInterface.contractApplyApproval({ ContractApprovalRecordId: this.approvalData.ContractApprovalRecordId }).then((res) => {
              if (res.Ret === 200) {
                this.show = false;
                this.form.reason = "";
                this.handleRefreshList()
                this.$message.success('审批成功')
              }
            });
          } else {
            contractInterface.contractApplyReject({ ContractApprovalRecordId: this.approvalData.ContractApprovalRecordId, Remark: this.form.reason }).then((res) => {
              if (res.Ret === 200) {
                this.show = false;
                this.form.reason = "";
                this.handleRefreshList()
                this.$message.success('驳回成功')
              }
            });
          }
        }
      });
    },

    //取消审批
    handleCancelApproval() {
      this.$refs.form.resetFields();
      this.show = false;
    },

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

    //查看详细操作说明
    explainDialog(){
      this.explainShowDownload=true;
    },

    formatChangeInfo(str){
      let arr=str.split('</n>').filter(item=> item)
      let arr2=arr.map(item=>{
        return `<p>${item}</p>`
      })
      return arr2.join('')
    },

    // 审批弹窗审批状态切换
    approvalFromStatusChange(){
      if(this.form.status==='驳回'){
        let top=$('.approval-wrap')[0].offsetTop
        $('.approval-wrap').animate({
          "scrollTop": top+1000
        })
      }
    }
  },
};
</script>

<style lang="scss">
.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>
.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;
  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;
  }
}
.approval-wrap {
  max-height: 70vh;
  overflow-y: scroll;
  display: flex;
  justify-content: space-between;
  .main {
    width: 75%;
    .table-wrap {
      width: 100%;
      // text-align: center;
      border-top: 1px solid #dcdfe6;
      border-left: 1px solid #dcdfe6;
      .table-item {
        padding: 14px 10px;
        border-right: 1px solid #dcdfe6;
        border-bottom: 1px solid #dcdfe6;
        position: relative;
      }
      .width-50 {
        width: 50%;
      }
    }
    .service-wrap {
      margin-top: 12px;
      font-size: 14px;
      display: flex;
      color: #333;
      .service_varieties{
        span{
          font-size: 14px;
          font-family: PingFang SC-Regular, PingFang SC;
          font-weight: 400;
          -webkit-background-clip: text;
        }
        #service_varieties_form{
          span{
            font-family: PingFang SC-Regular, PingFang SC;
            font-weight: 400;
            color: #3385FF;
            -webkit-background-clip: text;
            background: #EEF5FF;
            border-radius: 2px 2px 2px 2px;
            padding: 2px 5px;
            margin-right: 10px;
            word-break: keep-all;
            white-space: nowrap;
          }
        }
      }
    }
    .dashed-line {
      margin: 20px 0;
      border-top: 1px dashed #aab4cc;
    }
  }
  .right {
    width: 22%;
    .timeline-wrap {
      max-height: 500px;
      overflow-y: auto;
      margin-top: 20px;
      background-color: #fff;
      border: 1px solid #aab4cc;
      padding: 20px;
      border-radius: 4px;
      text-align: left;
      height: calc(100% - 120px);
    }
  }
}

.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>
