<template>
  <div class="flex addconstract-container">
    <el-form ref="form" :model="formData" label-position="left" :rules="formRule" label-width="110px" style="width: 80%">
      <section class="section">
        <h2 class="section-title">客户信息</h2>
        <div class="section-container">
          <div class="flex border-top" style="padding-top: 30px">
            <el-form-item label="甲方名称" prop="CompanyName" style="width: 50%">
              <!-- <el-input v-model="formData.CompanyName" placeholder="请输入名称" style="width: 350px"></el-input> -->
              <el-autocomplete
                v-model="formData.CompanyName"
                :fetch-suggestions="querySearchAsyncCustome"
                placeholder="请输入或者搜索客户名称"
                @select="handleSelectCustome"
                @blur="handleCustomeInputChange"
                style="width: 50%"
              ></el-autocomplete>
            </el-form-item>
            <el-form-item label="社会信用码" prop="CreditCode" style="width: 50%">
              <el-input v-model="formData.CreditCode" placeholder="请输入社会信用码" style="width: 350px" :disabled="cusLastcontract" @input="getContractByCode"></el-input>
              <!-- <span style="font-size:14px;color:#4099ef;cursor: pointer;" v-if="cusLastcontract" @click="handleUnbind">解除绑定</span> -->
            </el-form-item>
          </div>

          <div class="flex border-top" style="padding-top: 30px">
            <el-form-item label="公司地址" prop="Province" style="width: 50%">
              <v-distpicker :province-source="province_sorce"
                :city-source="city_sorce"  :province="formData.Province" :city="formData.City" hide-area @province="provinceChange" @selected="selectRegion"></v-distpicker>
            </el-form-item>
            <el-form-item label="详细地址" prop="address" style="width: 50%">
              <el-input v-model="formData.Address" placeholder="请输入详细地址" style="width: 350px"></el-input>
            </el-form-item>
          </div>

          <div class="flex border-top" style="padding-top: 30px">
            <el-form-item label="传真" prop="customeCz" style="width: 50%">
              <el-input v-model="formData.Fax" placeholder="请输入传真" style="width: 350px"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="customeTel" style="width: 50%">
              <el-input v-model="formData.Phone" placeholder="请输入电话" style="width: 350px"></el-input>
            </el-form-item>
          </div>
          <el-form-item label="邮编" prop="postCode" class="border-top">
            <el-input v-model="formData.Postcode" placeholder="请输入邮编" style="width: 350px"></el-input>
          </el-form-item>
        </div>
      </section>

      <section class="section">
        <h2 class="section-title">合同信息</h2>
        <div class="section-container">
          <div class="flex border-top" style="padding-top: 30px">
            <el-form-item label="合同编号" style="width: 50%">
              <span>{{ formData.ContractCode }}</span>
            </el-form-item>
            <el-form-item label="合同归属" style="width: 50%">
              <span>{{ formData.ProductId === 1 ? "FICC" : "权益" }}</span>
            </el-form-item>
          </div>
          <el-form-item label="合同类型" prop="ContractType" class="border-top">
            <el-radio-group v-model="formData.ContractType">
              <div style="display:flex">
                <div style="margin-right:10px;">
                  <el-radio label="新签合同" :disabled="contractTypeDisable1">新签合同</el-radio>
                  <el-tooltip effect="dark" style="cursor: pointer;width:20px;">
                    <div slot="content">没有正式转试用记录的客户，在申请转正时提交的合同</div>
                    <i class="el-icon-info" style="font-size:14px;margin-left:-20px"></i>
                  </el-tooltip>
                </div>
                <div style="margin-right:10px">
                  <el-radio label="续约合同" :disabled="contractTypeDisable2">续约合同</el-radio>
                  <el-tooltip effect="dark" style="cursor: pointer;width:20px;">
                    <div slot="content">
                      1、有正式转试用记录的客户，在申请转正时提交的合同<br>
										  2、所有客户在续约申请时提交的合同
                    </div>
                    <i class="el-icon-info" style="font-size:14px;margin-left:-20px"></i>
                  </el-tooltip>
                </div>
                <div style="margin-right:10px" v-if="RoleType!=='rai_seller'">
                  <el-radio label="补充协议" :disabled="contractTypeDisable3">补充协议</el-radio>
                </div>
              </div>
            </el-radio-group>
          </el-form-item>
          <div class="flex border-top">
            <el-form-item label="合同期限" prop="timeRange" style="width: 50%">
              <el-date-picker 
                v-model="formData.timeRange" 
                type="daterange" 
                value-format="yyyy-MM-dd" 
                range-separator="至" 
                start-placeholder="开始日期" 
                end-placeholder="结束日期" 
                :disabled="timeDisable"
                :picker-options="pickerOptions"> 
              </el-date-picker>
            </el-form-item>
            <span style="line-height: 40px">{{ formData.timeRange | formateYear }}</span>
          </div>

          <div class="flex border-top">
            <el-form-item label="合同金额" prop="OriginalPrice" style="width: 50%">
              <el-input v-model="formData.OriginalPrice"  @focus="handlePriceBoxFocus('OriginalPrice')" @blur="handlePriceBoxBlur('OriginalPrice')" placeholder="请输入合同金额" style="width: 220px"></el-input>
            </el-form-item>
            <span style="line-height: 40px">{{ formData.OriginalPrice | digitUppercase }}</span>
          </div>

          <div class="flex border-top">
            <el-form-item label="优惠后金额" prop="Price" style="width: 50%">
              <el-input v-model="formData.Price" @focus="handlePriceBoxFocus('Price')" @blur="handlePriceBoxBlur('Price')" placeholder="请输入优惠后金额" style="width: 220px"></el-input>
            </el-form-item>
            <span style="line-height: 40px">{{ formData.Price | digitUppercase }}</span>
          </div>

          <el-form-item label="付款方式说明" prop="PayRemark" class="border-top">
            <el-input type="textarea" v-model="formData.PayRemark" placeholder="请输入付款方式说明（请参考以下说明模板填写，请勿填写现金/转账等支付形式）" style="width: 80%"></el-input>
            <p>说明模板：甲方自合同生效日起的十日之内一次性支付一年服务费，乙方收款后为甲方开具合法有效的增值税发票。</p>
          </el-form-item>
          <el-form-item label="付款方" prop="PayChannel" class="border-top">
            <!-- <el-input type="textarea" v-model="formData.PayChannel" placeholder="填写代支付的券商名称/期货公司名称，若非代付填写无" style="width: 80%"></el-input> -->
            <!-- <el-autocomplete
              v-model="formData.PayChannel"
              :fetch-suggestions="querySearchAsyncPayChannel"
              placeholder="请输入"
              style="width: 80%"
            ></el-autocomplete> -->
            <el-select
                v-model="formData.PayChannel"
                multiple
                filterable
                remote
                allow-create
                placeholder="请输入关键词"
                :remote-method="querySearchAsyncPayChannel"
                style="width: 80%">
                <el-option
                  v-for="item in PayChannelOptions"
                  :key="item.PayChannel"
                  :label="item.PayChannel"
                  :value="item.PayChannel">
                </el-option>
              </el-select>
            <p>如果为代付，则需要填写代付方名称（期货公司或者证券公司），请勿填写现金/转账</p>
          </el-form-item>
          <!-- <el-form-item label="备注" prop="SellerRemark" class="border-top">
            <el-input type="textarea" v-model="formData.SellerRemark" placeholder="审批人查看，不在生成合同中展示" style="width: 80%"></el-input>
          </el-form-item> -->
        </div>
      </section>

      <section class="section">
        <h2 class="section-title">服务内容</h2>
        <div class="section-container">
          <!-- ficc 服务内容表格 -->
          <FiccServiceTable
            ref="FiccServiceTable"
            :canEdit="true"
            :serviceData="ficcServiceData"
            :hasSercive="selectServiceData"
            :editValue="editValue"
            :contractType="formData.ContractType"
            :isEdit="true"
            @handleShowService="handleShowService"
            v-if="RoleType === 'ficc_seller'"
          ></FiccServiceTable>
          <!-- 权益 服务内容表格 -->
          <QyServiceTable ref="QyServiceTable" :canEdit="true" :serviceData="qyServiceData" :hasSercive="selectServiceData" @handleShowService="handleShowService" v-else></QyServiceTable>
        </div>

        <p style="margin-top: 30px; margin-bottom: 20px">补充内容（eg额外赠送、路演次数规定）</p>
        <el-radio v-model="radio" label="2">无</el-radio>
        <el-radio v-model="radio" label="1">有</el-radio>
        <el-form-item prop="Remark" label-width="0" ref="formItemRemark">
          <el-input v-if="radio === '1'" type="textarea" v-model="formData.Remark" rows="5" placeholder="请输入内容" style="margin: 20px 0; display: block; box-sizing: border-box"></el-input>
        </el-form-item>
      </section>

      <section class="section">
        <h2 class="section-title">审批备注</h2>
        <div class="section-container">
          <el-form-item label="备注" prop="SellerRemark" class="border-top">
            <el-input type="textarea" v-model="formData.SellerRemark" placeholder="请输入备注（仅供审批人查看，不在生成合同中展示）" style="width: 80%"></el-input>
          </el-form-item>
        </div>
      </section>
    </el-form>
    <div class="right-wrap">
      <div style="text-align: center" v-if="currentRouteName === '编辑合同' || currentRouteName === '复制模板'||currentRouteName === '重审合同'||currentRouteName === '修改重审'">
        <el-button type="primary" plain style="width: 30%;min-width:70px;margin-bottom:10px" @click="handleOperation('存草稿')">存草稿</el-button>
        <el-button type="primary" style="width: 30%;margin-left:3%;min-width:70px;margin-bottom:10px" @click="handleOperation('预览')">预览</el-button>
        <el-button type="primary" style="width: 30%;margin-left:3%;min-width:70px;margin-bottom:10px" @click="handleOperation('提交')">提交</el-button>
      </div>
      <!-- <div style="text-align: center" v-if="currentRouteName === '重审合同'">
        <el-button type="primary" plain style="width: 30%;min-width:70px;margin-bottom:10px" @click="handleSave">存草稿</el-button>
        <el-button type="primary" style="width: 30%;min-width:70px" @click="handlePreview">预览</el-button>
        <el-button type="primary" style="width: 30%;min-width:70px" @click="handleSubmit">提交</el-button>
      </div> -->
      <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>

    <!-- 套餐 -->
    <ServiceDialog ref="ServiceDialog" :serviceShow="serviceShow" @serviceClose="serviceClose" @serviceSave="serviceSave" :serviceCon="serviceCon"></ServiceDialog>
  </div>
</template>

<script>
import { contractInterface,customInterence } from "@/api/api.js";
import{province_sorce,city_sorce} from '@/utils/distpicker';
import ServiceDialog from "./components/ServiceDialog"; //套餐内容弹窗组件
import QyServiceTable from "./components/QyServiceTable"; //权益服务内容表格组件
import FiccServiceTable from "./components/FiccServiceTable"; //ficc服务内容表格组件
import {CalculationDate} from '@/utils/CalculationDate'
export default {
  name: "EditConstract",
  components: {
    ServiceDialog,
    QyServiceTable,
    FiccServiceTable,
  },
  filters: {
    // 金额转中文大写
    digitUppercase(n) {
      if (n) {
        n=n.toString().replace(/,/g,'')
        let fraction = ["角", "分"];
        let digit = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
        let unit = [
          ["元", "万", "亿"],
          ["", "拾", "佰", "仟"],
        ];
        let head = n < 0 ? "欠" : "";
        n = Math.abs(n);
        let s = "";
        for (let i = 0; i < fraction.length; i++) {
          s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, "");
        }
        // s = s || "整";

        n = Math.floor(n);
        for (let i = 0; i < unit[0].length && n > 0; i++) {
          let p = "";
          for (let j = 0; j < unit[1].length && n > 0; j++) {
            p = digit[n % 10] + unit[1][j] + p;
            n = Math.floor(n / 10);
          }
          s = p.replace(/(零.)*零$/, "").replace(/^$/, "零") + unit[0][i] + s;
        }
        return (
          "大写：" + (head + s.replace(/(零.)*零元/, "元").replace(/(零.)+/g, "零"))
          // .replace(/^整$/, "零元整")
        );
      }
    },

    //计算多少年
    formateYear(e) {
      if (!e) return;
      if (e[0]) {
        return `有效期为${CalculationDate(e[0],e[1])}`
      } else {
        return "";
      }
    },
  },
  // computed: {
  //   pickerOptions(){
  //     console.log('aaa');
  //     let obj={disabledDate() {return false}}
  //     if(this.cusLastcontract){
  //       if(this.formData.ContractType==='续约合同'&&this.RoleType==='ficc_seller'){
  //         // ficc 起始日期为权限中最大的时间
  //         this.formData.timeRange=[]
  //         let timearr=this.cusLastcontract.map(item=> item.EndDate)
  //         let maxTime=Math.max.apply(null, timearr.map(item => (new Date(item)).getTime()));
  //         let endDate=this.formatDate(new Date(maxTime))
  //         obj={
  //           disabledDate(time) {
  //             return time.getTime() < new Date(endDate).getTime();
  //           }
  //         }
  //       }else{
  //         obj={
  //           disabledDate() {
  //               return false
  //             }
  //         }
  //       }
  //       if(this.formData.ContractType==='补充协议'){
  //         let today=this.formatDate(new Date())
  //         // 找出权限中最晚截止的那个作为截至日期
  //         let timearr=this.cusLastcontract.map(item=> item.EndDate)
  //         let maxTime=Math.max.apply(null, timearr.map(item => (new Date(item)).getTime()));
  //         let endDate=this.formatDate(new Date(maxTime))
  //         this.formData.timeRange=[today,endDate]
  //         this.timeDisable=true
  //         obj={disabledDate() {return true}}
  //       }else{
  //         this.timeDisable=false
  //       }
  //     }
      
  //     return obj
  //   },
  // },

  watch: {
    'formData.ContractType':{
      handler(nval){
        let obj={disabledDate() {return false}}
        if(this.cusLastcontract){
          if(nval==='续约合同'&&this.RoleType==='ficc_seller'){
            // ficc 起始日期为权限中最大的时间
            this.formData.timeRange=[]
            let timearr=this.cusLastcontract.map(item=> item.EndDate)
            let maxTime=Math.max.apply(null, timearr.map(item => (new Date(item)).getTime()));
            let endDate=this.formatDate(new Date(maxTime))
            console.log(endDate);
            obj={
              disabledDate(time) {
                return time.getTime() < new Date(endDate).getTime();
              }
            }
          }else{
            obj={
              disabledDate() {
                  return false
                }
            }
          }
          if(nval==='补充协议'){
            let today=this.formatDate(new Date())
            // 找出权限中最晚截止的那个作为截至日期
            let timearr=this.cusLastcontract.map(item=> item.EndDate)
            let maxTime=Math.max.apply(null, timearr.map(item => (new Date(item)).getTime()));
            let endDate=this.formatDate(new Date(maxTime))
            this.formData.timeRange=[today,endDate]
            obj={disabledDate() {return true}}
          }
        }

        if(nval==='补充协议'){
          this.timeDisable=true
        }else{
          this.timeDisable=false
        }
        this.pickerOptions=obj
      },
      immediate:true
    },
    radio(nval, oval) {
      this.$refs.formItemRemark.resetField();
      if (nval === "1") {
        this.formRule.Remark[0].required = true;
      } else {
        this.formRule.Remark[0].required = false;
      }
    },
  },
  
  data() {
    this.province_sorce=province_sorce
    this.city_sorce=city_sorce
    return {
      contractTypeDisable1:false,//能否选择新签合同
      contractTypeDisable2:false,//能否选择续约合同
      contractTypeDisable3:false,//能否选择补充协议
      pickerOptions:null,
      timeDisable:false,
      cusLastcontract:null,
     
      currentRouteName: this.$route.name,
      contractId: this.$route.query.contractId,
      operationList: [],
      RoleType: localStorage.getItem("Role") || "",
      radio: "1", //是否有补充内容 1有 2 无

      formData: {},
      formRule: {
        ContractType: [{ required: true, message: "请选择合同类型", trigger: "change" }],
        timeRange: [{ required: true, message: "请选择有效期限", trigger: "change" }],
        OriginalPrice: [
          { required: true, message: "请填写合同金额", trigger: "blur" },
          // { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: "请输入正确的格式,可保留两位小数" },
        ],
        PayRemark: [{ required: true, message: "请填写付款方式说明", trigger: "blur" }],
        CompanyName: [{ required: true, message: "请填写名称", trigger: "blur" }],
        CreditCode: [{ required: true, message: "请填写信用码", trigger: "blur" }],
        Province: [{ required: true, message: "请选择地址", trigger: "change" }],
        Remark: [{ required: true, message: "请填写补充说明", trigger: "blur" }],
        PayChannel:[{ required: true, message: "请填写付款方", trigger: "change" }]
      },
      ficcServiceData: [], //ficc服务内容
      qyServiceData: [], //权益服务内容
      serviceShow: false,
      serviceCon: {}, //选择的服务项 查看报价单/选择品种
      selectServiceData: [],
      editValue: {},
      PayChannelOptions:[],//搜索出付款方列表
    };
  },
  created() {
    this.getContractDetail();
    this.getContractOperationList();
  },
  methods: {
    // 社会信用码变更
    async getContractByCode(){
      this.contractTypeDisable1=false
      this.contractTypeDisable2=false
      this.contractTypeDisable3=false
      if(!this.formData.CreditCode) return
      const res=await contractInterface.getContractTypeByCode({CreditCode:this.formData.CreditCode})
      if(res.Ret==200){
        let customeId=res.Data.Item&&res.Data.Item.CompanyId
        if(customeId){
          const res2=await customInterence.applyTurnContractType({CompanyId:customeId}) 
          
          if(res2.Ret===200){
            if(res2.Data.ContractType==='新签合同'){
              this.formData.ContractType=res2.Data.ContractType
              this.contractTypeDisable1=false
              this.contractTypeDisable2=true
              this.contractTypeDisable3=true
            }else{
              if(this.RoleType==='ficc_seller'){
                this.contractTypeDisable1=true
                this.contractTypeDisable2=false
                this.contractTypeDisable3=false
              }
              if(this.RoleType==='rai_seller'){
                this.formData.ContractType=res2.Data.ContractType
                this.contractTypeDisable1=true
                this.contractTypeDisable2=false
                this.contractTypeDisable3=true
              }
            }
          }
        }
      }
    },

    // 解除搜索选中的客户绑定(需求修改不需要此操作2021-9-16)
    handleUnbind(){
      this.$confirm('此操作将解除与选择的客户绑定, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.contractTypeDisable1=false
        this.contractTypeDisable2=false
        this.contractTypeDisable3=false
        // this.pickerOptions={}
        this.cusLastcontract=null
        this.timeDisable=false
      }).catch(()=>{
        console.log('取消解绑');
      })
    },

    // 客户名称搜索框输入变化
    handleCustomeInputChange(e){
      // 将付款方初始化为客户名称
      // const flag=this.formData.PayChannel.includes(this.formData.CompanyName)
      // if(!flag){
      //   this.formData.PayChannel.push(this.formData.CompanyName)
      // }
    },

    // 搜索付款渠道
    // async querySearchAsyncPayChannel(queryString, cb){
    //   cb([])
    //   // if(!queryString) return
    //   let res=await contractInterface.getPayChannel({Keyword:queryString})
    //   if(res.Ret===200){
    //     if(res.Data&&res.Data.length>0){
    //       let arr=res.Data.map(item=>{
    //         return {value:item.PayChannel,...item}
    //       })
    //       cb(arr)
    //     }
    //   }
    // },
    // 付款渠道方式修改 多选
    async querySearchAsyncPayChannel(query,type){
      if(!type&&!query) return
      let res=await contractInterface.getPayChannel({Keyword:query})
      if(res.Ret===200){
        this.PayChannelOptions=res.Data||[]
      }
    },

    // 格式化时间
		formatDate(date){
			let year=date.getFullYear()
			let month=date.getMonth()+1
			let day=date.getDate()
			return `${year}-${month<10?'0'+month:month}-${day<10?'0'+day:day}`
		},

    // 初始化客户搜索动作
    async initCustomeSelect(queryString){
      let CompanyType=localStorage.getItem('RoleType')
      let res=await customInterence.customList({KeyWord:queryString,PageSize:10000,CompanyType:CompanyType,IncludeShare:true})
      if(res.Ret===200){
        if(res.Data.List&&res.Data.List.length>0){
          this.handleSelectCustome(res.Data.List[0])
        }
      }
    },

    // 客户搜索
    async querySearchAsyncCustome(queryString, cb){
      cb([])
      if(!queryString) return
      let CompanyType=localStorage.getItem('RoleType')
      let res=await customInterence.customList({KeyWord:queryString,PageSize:10000,CompanyType:CompanyType,IncludeShare:true})
      // this.contractTypeDisable1=false
      // this.contractTypeDisable2=false
      // this.contractTypeDisable3=false
      // // this.pickerOptions={}
      // this.cusLastcontract=null
      // this.timeDisable=false
      if(res.Ret===200){
        if(res.Data.List.length>0){
          let arr=res.Data.List.map(item=>{
            return {value:item.CompanyName,...item}
          })
          cb(arr)
        }
      }
    },

    //选择客户
    async handleSelectCustome(item){
      // 获取客户详情 更新表单数据
      let res=await customInterence.customDetail({CompanyId:item.CompanyId})
      if(res.Ret===200){
        this.formData.CreditCode=res.Data.Item.CreditCode
        this.formData.Province=res.Data.Item.Province
        this.formData.City=res.Data.Item.City
      }
      // 更新合同类型
      let res2=await customInterence.applyTurnContractType({CompanyId:item.CompanyId})
      if(res2.Ret===200){
        
        if(res2.Data.ContractType==='新签合同'){
          this.formData.ContractType=res2.Data.ContractType
          this.contractTypeDisable1=false
          this.contractTypeDisable2=true
          this.contractTypeDisable3=true
        }else{
          if(this.RoleType==='ficc_seller'){
            this.contractTypeDisable1=true
            this.contractTypeDisable2=false
            this.contractTypeDisable3=false
          }
          if(this.RoleType==='rai_seller'){
            this.formData.ContractType=res2.Data.ContractType
            this.contractTypeDisable1=true
            this.contractTypeDisable2=false
            this.contractTypeDisable3=true
          }
        }
      }

      // 获取客户大于今天的最后一份有效合同详情
      let res3=await customInterence.lastContractInfo({CompanyId:item.CompanyId})
      if(res3.Ret===200){
        if(res3.Data&&res3.Data.length>0){
          this.cusLastcontract=res3.Data
        }else{
          this.cusLastcontract=null
        }
        
      }
    },

    //判断合同期限 不小于一个月
    validateTime() {
      if(this.formData.ContractType==='补充协议') return true
      let start = new Date(this.formData.timeRange[0]).getTime();
      let end = new Date(this.formData.timeRange[1]).getTime();
      let oneMonth = 1000 * 60 * 60 * 24 * 29;
      if (end - start >= oneMonth) {
        return true;
      } else {
        this.$message.warning("合同期限不能小于一个月");
        return false;
      }
    },

    //判断优惠后金额不能大于合同金额
    validatePrice() {
      if (Number(this.formData.Price) > Number(this.formData.OriginalPrice)) {
        this.$message.warning("优惠后金额不得大于合同金额");
        return false;
      } else {
        return true;
      }
    },

    // 判断小套餐中是否选择品种/新增的行是否有数据
    validateService(data) {
      //判断品种列是否有值
      let arr = [];
      data.forEach((item) => {
        item.forEach((item2) => {
          if (item2.HeadName === "品种") {
            arr.push(...item2.ValueId);
          }
        });
      });
      // 判断行是否有值
      let arr2 = [];
      data.forEach((item, index) => {
        let arr = item.filter((item2) => {
          if (!item2.Value) return item2;
        });
        if (arr.length === item.length) {
          arr2.push(index);
        }
      });

      if (!arr.length&&this.formData.ContractType!=='补充协议') {
        this.$message.warning("至少选择一个品种");
        return false;
      }

      if (arr2.length) {
        this.$message.warning("行内至少填一项");
        return false;
      }

      return true;
    },

    //获取合同操作记录
    getContractOperationList() {
      contractInterface.getContractOperationList({ ContractId: this.contractId }).then((res) => {
        if (res.Ret === 200) {
          this.operationList = res.Data.List;
        }
      });
    },

    //选地地区时 选则的省份改变重置city为空
    provinceChange(e){
      if(e.value!=this.formData.Province){
        // this.formData.City=''
        this.formData.Province=e.value
      }
    },

    //选择地区
    selectRegion(e) {
      this.formData.Province = e.province.value=='省'?'':e.province.value;
      this.formData.City = e.city.value=='市'?'':e.city.value;
    },

    // 判断套餐权限
    handleValidate(e){
      let tag=true
      let tagsmall=false
      // ficc 补充协议 不允许有选择过的
      if(this.RoleType === "ficc_seller"&&e.ContractType==='补充协议'){
        // 是否选择大套餐 大套餐为全部品种 不能选
        e.Service.forEach(item=>{
          // 大套餐
          if(item.ChartPermissionId===0&&item.ServiceTemplateId===1){
            tag=false
            this.$message.warning('FICC大套餐不可选')
          }
          // 小套餐 判断其中ficc周报是否有重复选择的权限
          if(item.ChartPermissionId===0&&item.ServiceTemplateId===2){
            let temIdarr=[]
            item.Detail.forEach(item2=>{
              item2.forEach(item3=>{
                if(item3.Value==='FICC周报'){
                  item2.forEach(item4=>{
                    if(item4.HeadName==='品种'){
                      temIdarr=item4.ValueId
                    }
                  })
                }
              })
            })

            this.cusLastcontract.forEach(item4=>{
              if(temIdarr.indexOf(item4.ChartPermissionId)!=-1){
                tag=false
                tagsmall=true
                // this.$message.warning('小套餐中权限重复')
              }
            })
          }

          // 市场策略
          if(item.ChartPermissionId!==0){
            this.cusLastcontract.forEach(item2=>{
              if(item2.ChartPermissionId===item.ChartPermissionId){
                this.$message.warning(`${item.Title}不可选`)
                tag=false
              }
            })
          }
        })
      }

      // 权益 续约合同 
      if(this.RoleType === "rai_seller"&&e.ContractType==='续约合同'){
        const time1=new Date(this.formData.timeRange[0]).getTime()//选择的开始时间
        const time2=new Date(this.formData.timeRange[1]).getTime()//选择的结束时间
        this.cusLastcontract.forEach(item=>{
          const time3=new Date(item.StartDate).getTime()
          const time4=new Date(item.EndDate).getTime()
          if(time1>time4||time2<time3){
            console.log('选择时间和上一份无重叠');
          }else{
            console.log('时间重叠');
            e.Service.forEach(item2=>{
              console.log(item2.ChartPermissionId,item.ChartPermissionId);
              if(item2.ChartPermissionId===item.ChartPermissionId){
                this.$message.warning('同行业有重叠的合同期限，请核实后再提交')
                tag=false
              }
            })

          }
        })
        
      }

      // 小套餐统一一个提示
      if(tagsmall){
        this.$message.warning('小套餐中权限重复')
      }
      return tag
    },

    //提交表单 存草稿、预览、提交
    handleOperation:_.debounce(function(submitType) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let temarr = [];
          if (this.RoleType === "ficc_seller") {
            this.$refs.FiccServiceTable.tableData.forEach((item) => {
              let obj = {
                ServiceTemplateId: "",
                Value: "",
                Detail: [],
                Title: item.Title,
                ChartPermissionId:item.ChartPermissionId
              };
              obj.ServiceTemplateId = item.ServiceTemplateId;
              obj.Value = item.Value;
              if (item.selected) {
                //小套餐情况
                if (item.Detail) {
                  if (this.$refs.ServiceDialog.tableHeadData.length === 0) {
                    let arr = [];
                    this.formData.Service.forEach((item2) => {
                      if (item2.ServiceTemplateId === item.ServiceTemplateId) {
                        arr = item2.DetailList.map((rowItem) => {
                          let rowArr = [];
                          for (let key in rowItem) {
                            if (key.substr(0, 3) === "Col" && rowItem[key] !== "") {
                              rowArr.push(JSON.parse(rowItem[key]));
                            }
                          }
                          return rowArr;
                        });
                      }
                    });
                    obj.Detail = arr;
                  } else {
                    obj.Detail = [this.$refs.ServiceDialog.tableHeadData, ...this.$refs.ServiceDialog.tableData];
                  }
                }
                temarr.push(obj);
              }
            });
          } else {
            // 只要一个分类里面 主观和客观其中一个被勾选 这个分类就要传
            this.$refs.QyServiceTable.selectAllArr.map(item =>{
              if(this.$refs.QyServiceTable.checkList.find(it => it.indexOf(item.name)!=-1 && it.indexOf("升级")==-1)){
                temarr.push({
                  ServiceTemplateId: item.ServiceTemplateId,
                  Value: item.value,
                  Detail: null,
                  Title: item.name,
                  ChartPermissionId:item.ChartPermissionId
                })
              }
            })
            this.$refs.QyServiceTable.tableData.list.forEach((item) => {
              let obj = {
                ServiceTemplateId: "",
                Value: "",
                Detail: null,
                Title: item.Title,
                Title: item.Title == item.fatherName ? item.Title:`${item.fatherName}（${item.Title}）`,
                ChartPermissionId:item.ChartPermissionId
              };
              obj.ServiceTemplateId = item.ServiceTemplateId;
              obj.Value = item.Value;
              let flag = ''
              if(item.Title == item.fatherName){
                //没有主客观
                 flag= this.$refs.QyServiceTable.checkList.indexOf(item.Title);
              }else{
                flag= this.$refs.QyServiceTable.checkList.indexOf(`${item.fatherName}（${item.Title}）`);
              }
              if (flag !== -1) {
                temarr.push(obj);
              }
            });
          }

          // 判断地址
          if(this.formData.Province!='海外'&&!this.formData.City){
            this.$message.warning('请选择地址')
            return
          }

          // 判断合同期限 不小于一个月
          if (!this.validateTime()) {
            return;
          }
          //判断金额
          if (!this.validatePrice()) {
            return;
          }
          //判断是否选择了套餐
          if(!temarr.length){
            this.$message.warning('请选择套餐')
            return
          }

          //判断小套餐
          let flag = true;
          temarr.forEach((item) => {
            if (item.Detail&&item.Detail.length) {
              flag = this.validateService(item.Detail.slice(1));
            }
          });
          if (!flag) return;

          let params = {
            ContractType: this.formData.ContractType,
            ContractBusinessType:"业务合同",
            StartDate: this.formData.timeRange[0],
            EndDate: this.formData.timeRange[1],
            OriginalPrice: Number(this.formData.OriginalPrice.toString().replace(/,/g,'')),
            Price: Number(this.formData.Price.toString().replace(/,/g,'')),
            PayRemark: this.formData.PayRemark,
            CompanyName: this.formData.CompanyName,
            CreditCode: this.formData.CreditCode,
            Province: this.formData.Province,
            City: this.formData.City,
            Address: this.formData.Address,
            Fax: this.formData.Fax,
            Phone: this.formData.Phone,
            Postcode: this.formData.Postcode,
            Remark: this.formData.Remark,
            PayChannel:this.formData.PayChannel.join(','),
            SellerRemark:this.formData.SellerRemark,
            TemplateId: this.RoleType === "ficc_seller" ? 1 : 2,
            Service: temarr,
          };

          console.log(params);
          // 判断套餐权限
          if(this.cusLastcontract&&!this.handleValidate(params)) return

          // 存草稿
          if(submitType==='存草稿'){
            this.handleSave(params)
          }

          //预览
          if(submitType==='预览'){
            this.handlePreview(params)
          }

          //提交
          if(submitType==='提交'){
            this.handleSubmit(params)
          }
        }else{
          this.$message.warning('请完善必填项')
        }
      });
    },200),

    //存草稿
    handleSave(params){
      
      let type = this.$route.query.type;
      // 复制模板(copy) 
      if (type === "copy") {
        params = {
          SourceId: this.formData.ContractId,
          ...params,
          IsAudit: false,
        };
        contractInterface.addContract(params).then((res) => {
          if (res.Ret === 200) {
            this.$router.go(-1);
          }
        });
      }
      // 申请重审(applyRetrial) 修改合同(modifyConstract) 编辑(edit)修改重审(modifyAndApply)
      if (type === "applyRetrial" || type === "modifyConstract" || type === "edit"||type==='modifyAndApply') {
        params = {
          ContractId: this.formData.ContractId,
          ...params,
          ReAudit:false
        };
        contractInterface.editContract(params).then((res) => {
          if (res.Ret === 200) {
            this.$router.go(-1);
          }
        });
      }
        
    },

    //预览
    handlePreview(params) {
      contractInterface.previewContract(params).then((res) => {
        if (res.Ret === 200) {
          sessionStorage.setItem("contractdtl", res.Data.Html);
          let { href } = this.$router.resolve({ path: "/contractdtl" });
          window.open(href, "_blank");
        }
      }); 
    },

    //提交
    handleSubmit(params){
      let type = this.$route.query.type;
      // 复制模板(copy) 
      if (type === "copy") {
        params = {
          SourceId: this.formData.ContractId,
          ...params,
          IsAudit: true,
        };
        contractInterface.addContract(params).then((res) => {
          if (res.Ret === 200) {
            this.$router.go(-1);
          }
        });
      }
      // 申请重审(applyRetrial) 修改合同(modifyConstract) 编辑(edit)修改重审(modifyAndApply)
      if (type === "applyRetrial" || type === "modifyConstract" || type === "edit"||type==='modifyAndApply') {
        params = {
          ContractId: this.formData.ContractId,
          ...params,
        };
        contractInterface.editContract(params).then((res) => {
          if (res.Ret === 200) {
            this.$router.go(-1);
          }
        });
      }
    },


    //获取合同详情
    getContractDetail() {
      contractInterface.getContractDetail({ ContractId: Number(this.contractId) }).then((res) => {
        if (res.Ret === 200) {
          this.formData = { ...res.Data, timeRange: [res.Data.StartDateStr, res.Data.EndDateStr] };
          this.formData.PayChannel=res.Data.PayChannel.split(',')||['无']
          if (res.Data.Remark) {
            this.radio = "1";
          } else {
            this.radio = "2";
          }
          this.selectServiceData = res.Data.Service;
          this.getServiceList();
          this.initCustomeSelect(res.Data.CreditCode)
        }
      });
    },

    //获取服务套餐模板数据
    getServiceList() {
      let ProductId = this.RoleType === "ficc_seller" ? 1 : 2;
      contractInterface.getServiceList({ ProductId }).then((res) => {
        if (res.Ret === 200) {
          if (this.RoleType === "ficc_seller") {
            this.ficcServiceData = res.Data;
          } else {
            this.qyServiceData = res.Data;
          }
        }
      });
    },

    //小套餐点击保存 更新数据
    serviceSave(e) {
      this.editValue = { ServiceTemplateId: e.ServiceTemplateId, Value: e.Value, tableData: e.tableData, tableHeadData: e.tableHeadData };
      // this.ficcServiceData.forEach((item) => {
      //   if (item.ServiceTemplateId === e.ServiceTemplateId) {
      //     item.Value = e.Value;
      //   }
      // });
      // this.selectServiceData.forEach((item) => {
      //   if (item.ServiceTemplateId === e.ServiceTemplateId) {
      //     item.Value = e.Value;
      //   }
      // });
    },

    //显示查看报价单弹窗
    handleShowService(e) {
      this.serviceCon = e;
      this.serviceShow = true;
    },

    //关闭查看报价单弹窗
    serviceClose() {
      this.serviceShow = false;
    },

    // 金额输入框获取焦点
    handlePriceBoxFocus(key){
      let val=this.formData[key].toString()
      val=val.replace(/,/g,'')
      this.formData[key]=val
    },
    // 金额输入框获失去焦点
    handlePriceBoxBlur(key){
      let str=this.formData[key].toString()
      let num1='',num2=''
      if(str.indexOf(".")!=-1){
        num1=str.substring(0,str.indexOf("."))
        num2=str.substring(str.length,str.indexOf("."))
        if(Number(num2)<=0){
          num2=''
        }
      }else{
        num1=str
      }
      this.formData[key]=num1.replace(/(?!^)(?=(\d{3})+$)/g, ',')+num2
    }
  },
};
</script>

<style>
.el-radio__input.is-checked .el-radio__inner {
  background-color: transparent;
}
.el-radio__inner::after {
  width: 6px;
  height: 6px;
  background-color: #409eff;
}
.el-checkbox__label {
  font-size: 16px !important;
}
.el-form-item {
  margin-bottom: 30px;
}
.el-input.is-disabled .el-input__inner {
  color: #606266;
}
.el-radio__input.is-disabled + span.el-radio__label {
  color: #606266;
}
.el-range-editor.is-disabled input {
  color: #606266;
}
.el-textarea.is-disabled .el-textarea__inner {
  color: #606266;
}
.el-timeline-item__tail {
  border-left: 2px solid #409eff;
}
</style>

<style lang="scss" scoped>
.addconstract-container {
  min-height: calc(100vh - 250px);
  position: relative;
  font-size: 16px;
  color: #000;
}
.flex {
  display: flex;
}
.section {
  background-color: #fff;
  border: 1px solid #aab4cc;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
  .section-title {
    margin-bottom: 30px;
  }
  .border-top {
    padding-top: 30px;
    border-top: 1px solid #dcdfe6;
  }
}

.right-wrap {
  margin-left: 20px;
  flex: 1;
  .timeline-wrap {
    margin-top: 10px;
    background-color: #fff;
    border: 1px solid #aab4cc;
    padding: 20px;
    border-radius: 4px;
    text-align: left;
    height: calc(100% - 120px);
    max-height: 1130px;
    overflow-y: auto;
  }
}
</style>
