<script setup>
import { ref,reactive,computed,watch } from "vue";
import {ElMessage,ElMessageBox} from "element-plus"
import { useRouter,useRoute} from 'vue-router';
import _ from 'lodash'
import { InfoFilled } from '@element-plus/icons-vue'

import { contractInterface,customInterence } from "@/api/api.js";
import{province_sorce,city_sorce} from '@/utils/distpicker';
import ServiceDialog from "./components/ServiceDialog.vue"; //套餐内容弹窗组件
import QyServiceTable from "./components/QyServiceTable.vue"; //权益服务内容表格组件
import FiccServiceTable from "./components/FiccServiceTable.vue"; //ficc服务内容表格组件
import {CalculationDate} from '@/utils/CalculationDate'

const $route = useRoute()
const $router = useRouter()

const province_sorce_value=province_sorce
const city_sorce_value=city_sorce

const contractTypeDisable1=ref(false) //能否选择新签合同
const contractTypeDisable2=ref(false) //能否选择续约合同
const contractTypeDisable3=ref(false) //能否选择补充协议
const pickerOptions=ref(null)
const timeDisable=ref(false)
const cusLastcontract=ref(null)
const RoleType=ref(localStorage.getItem("Role") || "")
const radio=ref('1')//是否有补充内容 1有 2 无

const currentRouteName=ref($route.meta.title)
const contractId=ref($route.query.contractId)
const operationList=ref([])
const formData=ref({})
const 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" }]
}

const ficcServiceData=ref([])//ficc服务内容
const qyServiceData=ref([])//权益服务内容
const serviceShow=ref(false)
const serviceCon=ref({})//选择的服务项 查看报价单/选择品种
const selectServiceData=ref([])
const editValue=ref({})//修改小套餐的value
const PayChannelOptions=ref([])//搜索出付款方列表

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

  if(nval==='补充协议'){
    timeDisable.value=true
  }else{
    timeDisable.value=false
  }
  pickerOptions.value=obj
},
{immediate:true})

const formItemRemark=ref(null)
watch(radio,(nval, oval)=>{
  formItemRemark.value.resetField();
  if (nval === "1") {
    formRule.Remark[0].required = true;
  } else {
    formRule.Remark[0].required = false;
  }
})

// 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
//   },
// },

// filters
// 金额转中文大写
const 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(/^整$/, "零元整")
    );
  }
}

//计算多少年
const formateYear=(e)=>{
  if (!e) return;
  if (e[0]) {
    return `有效期为${CalculationDate(e[0],e[1])}`
  } else {
    return "";
  }
}

// 社会信用码变更
const getContractByCode=async()=>{
  contractTypeDisable1.value=false
  contractTypeDisable2.value=false
  contractTypeDisable3.value=false
  if(!formData.value.CreditCode) return
  const res=await contractInterface.getContractTypeByCode({CreditCode:formData.value.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==='新签合同'){
          formData.value.ContractType=res2.Data.ContractType
          contractTypeDisable1.value=false
          contractTypeDisable2.value=true
          contractTypeDisable3.value=true
        }else{
          if(RoleType.value==='ficc_seller'){
            contractTypeDisable1.value=true
            contractTypeDisable2.value=false
            contractTypeDisable3.value=false
          }
          if(RoleType.value==='rai_seller'){
            formData.value.ContractType=res2.Data.ContractType
            contractTypeDisable1.value=true
            contractTypeDisable2.value=false
            contractTypeDisable3.value=true
          }
        }
      }
    }
  }
}

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

// 客户名称搜索框输入变化
const 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)
//     }
//   }
// },

// 付款渠道方式修改 多选
const querySearchAsyncPayChannel=async (query,type)=>{
  if(!type&&!query) return
  let res=await contractInterface.getPayChannel({Keyword:query})
  if(res.Ret===200){
    PayChannelOptions.value=res.Data||[]
  }
}

// 格式化时间
const 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}`
}

// 初始化客户搜索动作
const initCustomeSelect=async(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){
      handleSelectCustome(res.Data.List[0])
    }
  }
}

// 客户搜索
const querySearchAsyncCustome=async(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)
    }
  }
}

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

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

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

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

// 判断小套餐中是否选择品种/新增的行是否有数据
const 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&&formData.value.ContractType!=='补充协议') {
    ElMessage.warning("至少选择一个品种");
    return false;
  }

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

  return true;
}

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

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

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

// 判断套餐权限
const handleValidate=(e)=>{
  let tag=true
  let tagsmall=false
  // ficc 补充协议 不允许有选择过的
  if(RoleType.value === "ficc_seller"&&e.ContractType==='补充协议'){
    // 是否选择大套餐 大套餐为全部品种 不能选
    e.Service.forEach(item=>{
      // 大套餐
      if(item.ChartPermissionId===0&&item.ServiceTemplateId===1){
        tag=false
        ElMessage.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
                }
              })
            }
          })
        })

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

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

  // 权益 续约合同 
  if(RoleType.value === "rai_seller"&&e.ContractType==='续约合同'){
    const time1=new Date(formData.value.timeRange[0]).getTime()//选择的开始时间
    const time2=new Date(formData.value.timeRange[1]).getTime()//选择的结束时间
    cusLastcontract.value.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){
            ElMessage.warning('同行业有重叠的合同期限，请核实后再提交')
            tag=false
          }
        })

      }
    })
    
  }

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

const formRef=ref(null)
const FiccServiceTableRef=ref(null)
const QyServiceTableRef=ref(null)
const ServiceDialogRef=ref(null)
//提交表单 存草稿、预览、提交
const handleOperation=_.debounce(function(submitType) {
  formRef.value.validate((valid) => {
    if (valid) {
      let temarr = [];
      if (RoleType.value === "ficc_seller") {
        FiccServiceTableRef.value.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 (ServiceDialogRef.value.tableHeadData.length === 0) {
                let arr = [];
                formData.value.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 = [ServiceDialogRef.value.tableHeadData, ...ServiceDialogRef.value.tableData];
              }
            }
            temarr.push(obj);
          }
        });
      } else {
        // 只要一个分类里面 主观和客观其中一个被勾选 这个分类就要传
        QyServiceTableRef.value.selectAllArr.map(item =>{
          if(QyServiceTableRef.value.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
            })
          }
        })
        QyServiceTableRef.value.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= QyServiceTableRef.value.checkList.indexOf(item.Title);
          }else{
            flag= QyServiceTableRef.value.checkList.indexOf(`${item.fatherName}（${item.Title}）`);
          }
          if (flag !== -1) {
            temarr.push(obj);
          }
        });
      }

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

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

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

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

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

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

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

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

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

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

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


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

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

//小套餐点击保存 更新数据
const serviceSave=(e)=>{
  editValue.value = { 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;
  //   }
  // });
}

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

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

// 金额输入框获取焦点
const handlePriceBoxFocus=(key)=>{
  let val=formData.value[key].toString()
  val=val.replace(/,/g,'')
  formData.value[key]=val
}
// 金额输入框获失去焦点
const handlePriceBoxBlur=(key)=>{
  let str=formData.value[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
  }
  formData.value[key]=num1.replace(/(?!^)(?=(\d{3})+$)/g, ',')+num2
}

getContractDetail();
getContractOperationList();

</script>

<template>
  <div class="flex addconstract-container">
    <el-form ref="formRef" :model="formData" label-position="left" :rules="formRule" label-width="110px" style="width: 80%"
    size="large">
      <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_value"
                :city-source="city_sorce_value"  :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;">
                    <template #content>没有正式转试用记录的客户，在申请转正时提交的合同</template>
                    <el-icon :size="16" style="margin-left:-20px"><InfoFilled /></el-icon>
                  </el-tooltip>
                </div>
                <div style="margin-right:10px">
                  <el-radio label="续约合同" :disabled="contractTypeDisable2">续约合同</el-radio>
                  <el-tooltip effect="dark" style="cursor: pointer;width:20px;">
                    <template #content>
                      1、有正式转试用记录的客户，在申请转正时提交的合同<br>
										  2、所有客户在续约申请时提交的合同
                    </template>
                    <el-icon :size="16" style="margin-left:-20px"><InfoFilled /></el-icon>
                  </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 
                style="max-width: 350px;"
                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">{{ formateYear(formData.timeRange) }}</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">{{ digitUppercase(formData.OriginalPrice) }}</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">{{ digitUppercase(formData.Price) }}</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="FiccServiceTableRef"
            :canEdit="true"
            :serviceData="ficcServiceData"
            :hasSercive="selectServiceData"
            :editValue="editValue"
            :contractType="formData.ContractType"
            :isEdit="true"
            @handleShowService="handleShowService"
            v-if="RoleType === 'ficc_seller'"
          ></FiccServiceTable>
          <!-- 权益 服务内容表格 -->
          <QyServiceTable ref="QyServiceTableRef" :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('存草稿')" size="large">存草稿</el-button>
        <el-button type="primary" style="width: 30%;margin-left:3%;min-width:70px;margin-bottom:10px" @click="handleOperation('预览')" size="large">预览</el-button>
        <el-button type="primary" style="width: 30%;margin-left:3%;min-width:70px;margin-bottom:10px" @click="handleOperation('提交')" size="large">提交</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="ServiceDialogRef" :serviceShow="serviceShow" @serviceClose="serviceClose" @serviceSave="serviceSave" :serviceCon="serviceCon"></ServiceDialog>
  </div>
</template>

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