<script setup>
  import '../style/contractRegistration.scss'
  import scrollableSelect from '@/components/scrollable-select/index.vue'
  import permissionDia from '../components/permissionDia.vue'
  import permissionQyDia from '../components/permissionQyDia.vue'
  import {getContractSearchList,getServiceDetail} from '@/api/crm'
  import {registerAdd,registerEdit,contractRegisterCheck} from '@/api/financialMana'
  import financialCommon from '../composition/common'

  const contractSourceArray=['非CRM合同导入','CRM合同导入']
  const contractOwnereArray=['实际使用方','代付方']
  // 合同状态数组
  const contractStatusArray=financialCommon().contractStatusArray
  // 合同类型数组
  const contractTypeArray=financialCommon().contractTypeArray


  const props=defineProps({
    // 权限类型
    operationtype:{
      type:String,
      default:'compliance'
    },
    // 货币数据
    currencyList:{
      type:Array,
      default:()=>[]
    },
    // 套餐数据
    serviceItem:{
      type:Object,
      default:()=>{}
    },
    // 销售数据
    sellerData:{
      type:Object,
      default:()=>{}
    },
    // 预登记数据
    supplementaryInfo:{
      type:Object,
      default:()=>{}
    },
    // 详情数据
    detailInfo:{
      type:Object,
      default:()=>{}
    }
  })

  const emits=defineEmits(['submitSuccess'])

  const contractInfoForm=ref(null)
  // 表单相关
  const compliance=reactive({
    // 合规登记表单
    form:{
      product_ids:'',
      supplement:0, // 是否是补录合同
      contract_register_id:0,
      crm_contract_id:0,
      contract_source:0,
      contract_code:'',
      company_name:'',
      currency_unit:'CNY',
      seller_ids:'',
      seller_id:0,
      contract_status:'',
      start_date:'',
      end_date:'',
      contract_amount:'',
      contract_type:'', // 1-新签 2-续约 4-补充
      has_payment:'', // 0-自付 1-代付
      has_invoice:'', // 是否走开票带到款 0-否 1-是
      actual_pay_companies:'',
      relate_contract_code:'',
      relate_contract_main_code:'',
      sign_date:'',
      agreed_pay_time:'',
      // 套餐金额
      service_amount:[],
      services:[],
      services_amount:'',
      services_Qy_amount:'',
      service_remark:'',
      remark:""
    },
    rules:{
      contract_source:{required:true,message:'合同来源不能为空',trigger:'change'},
      contract_code:{required:true,message:'合同编号不能为空',trigger:'blur'},
      company_name:{required:true,message:'客户名称不能为空',trigger:'blur'},
      seller_ids:{required:true,message:'销售姓名不能为空',trigger:['blur','change']},
      contract_status:{required:true,message:'合同状态不能为空',trigger:'change'},
      start_date:{required:true,message:'合同有效期不能为空',trigger:'change'},
      contract_amount:[{required:true,message:'合同金额不能为空',trigger:'blur'},
      {
        validator:(rule,value,callback)=>{
          if(!parseFloat(value)){
            callback(new Error('合同金额格式错误'))
          }else{
            callback()
          }
        },
        trigger:'blur'
      }],
      contract_type:{required:true,message:'合同类型不能为空',trigger:'change'}
    },
    // 有效期
    contractValidityDate:[],
    // 合同类型选中
    contractTypeCheck:[],
    hasQYSeller:''
  })

  // --------------套餐信息
  const serviceData=reactive({
    // 选中的套餐 - ficc
    checkedService:[],
    // 选中的套餐 - 权益
    checkedServiceQy:[],
    // 小套餐选中的品种
    checkedPermission:[],
    // 权益大套餐选中的品种
    checkedPermissionQyBig:[],
    // 行业套餐选中的品种
    checkedPermissionQySmall:[],
    // 显示选择品种 - FICC小套餐
    serviceVarietyShow:false,
    serviceVarietyShowQy:false,
    // 1-大套餐  2-小套餐
    serviceType:0,
    // 权益套餐 1、权益大套餐 2、行业套餐
    serviceTypeQy:0,
    // 品种选择 - Ficc
    varietyDiaShow:false,
    //品种选择 - Qy
    varietyDiaShowQy:false,
    varietyDiaType:'view',
    // 1 - 权益大套餐 2-行业套餐 
    qYDiaType:1,
    // 查看套餐弹窗
    serviceShow:false,
  })

  // 销售列表类型1-单Ficc 2-单权益 3-ficc和权益
  const sellerListType=ref(3)
  // 选中的销售数组
  const cascaderSelectSeller=ref([])
  // 查看套餐报价单 图片
  const previewImage=ref('')
  // 查看套餐报价单 标题
  const previewImageTitle=ref('')

  // 合同编号列表请求参数
  const contractNoQuery=reactive({
    page_size:20,
    current:1,
    keyword:''
  })
  const contractNoInfo=reactive({
    contractNoTotal:0,
    contractNoLoading:false,
    contractNoArray:[]
  })

  // --------------------------------------方法
  // 合同来源改变
  const contractSourceChange=(value)=>{
    // 切换来源，清空数据
    compliance.form.product_ids='',
    compliance.form.crm_contract_id=0,
    compliance.form.contract_code='',
    compliance.form.company_name='',
    compliance.form.currency_unit='CNY',
    compliance.form.seller_ids='',
    compliance.form.seller_id='',
    compliance.form.contract_status='',
    compliance.form.start_date='',
    compliance.form.end_date='',
    compliance.form.contract_amount='',
    compliance.form.contract_type='',
    compliance.form.has_payment='',
    compliance.form.has_invoice='',
    compliance.form.actual_pay_companies='',
    compliance.form.relate_contract_code='',
    compliance.form.relate_contract_main_code='',
    compliance.form.sign_date='',
    compliance.form.agreed_pay_time='',
    compliance.form.services=[],
    compliance.form.services_amount='',
    compliance.form.services_Qy_amount='',
    compliance.form.service_remark='',
    compliance.form.remark=""

    compliance.hasQYSeller=''
    cascaderSelectSeller.value=[]

    serviceData.checkedService=[]
    serviceData.checkedServiceQy=[]
    serviceData.checkedPermission=[]
    serviceData.checkedPermissionQyBig=[]
    serviceData.checkedPermissionQySmall=[]
    sellerListType.value = value==0?3:''
    // 1-大套餐  2-小套餐
    serviceData.serviceType=0
    serviceData.serviceTypeQy=0
    // 品种选择 - Ficc
    serviceData.serviceVarietyShow=false
    // 品种选择 - Qy
    serviceData.serviceVarietyShowQy=false
    compliance.contractTypeCheck=[]
    compliance.contractValidityDate=[]
    setTimeout(()=>{
      // 去除错误信息
      contractInfoForm.value && contractInfoForm.value.clearValidate()
    },0)
  }
// ---------------------------------------计算
  const onlyQYSellerData=computed(()=>{
    return props.sellerData.all_list.filter(item => item.seller_id==5)[0].child
  })
  const onlyFICCSellerData=computed(()=>{
    return props.sellerData.all_list.filter(item => item.seller_id==2)[0].child
  })
// ------------------------------------------------监听
  watch(()=>props.supplementaryInfo.supplement,(value)=>{
    if(value){
      setSupplementaryData()
    }
  }) 

  watch(()=>props.detailInfo.contract_register_id,(value)=>{
    if(value){
      setComplianceDetail()
    }
  }) 
  
// --------------------------------------------------------方法

  // 合同类型改变
  const contractTypeChange=(value)=>{
    if(!value) return 
    compliance.form.has_payment = value[0]
    if(compliance.form.has_payment==0){
      compliance.form.has_invoice=1
    }
    // 新签 -- 新客户 其余的算老客户
    compliance.form.contract_type = value[1]
    if(compliance.form.contract_type!=4){
      // 新签、续约
      compliance.form.relate_contract_main_code=''
    }
    if(!compliance.form.has_payment){
      compliance.form.relate_contract_code=''
      compliance.form.actual_pay_companies=''
    }
  }

  // 销售修改
  const sellerChange=(value)=>{
    let ficcSeller,qySeller

    if(value?.length>0){
      for (let i = 0; i < value.length; i++) {
        const element = value[i];
        if(element[0]==2){
          // ficc
          ficcSeller = element[element.length-1]
        }else if(element[0]==5){
          //权益
          qySeller = element[element.length-1]
        }
      }
      cascaderSelectSeller.value=[ficcSeller,qySeller]
      compliance.hasQYSeller=qySeller?true:false
      compliance.form.seller_ids= cascaderSelectSeller.value.join(',')
    }else{
      cascaderSelectSeller.value=[]
      compliance.form.seller_ids=''
      compliance.hasQYSeller=''
    }
  }
  // 合同编号选中
  const selectContractNo=(value)=>{
    let selectItem=contractNoInfo.contractNoArray.find(item=>item.contract_code == value)
    if(selectItem.contract_business_type_int==2){
      // 代付合同
      compliance.form.has_payment=1
      compliance.form.has_invoice=1
      compliance.form.company_name=selectItem.actual_company_name
      compliance.form.relate_contract_code=selectItem.relate_contract_code
      compliance.form.actual_pay_companies=selectItem.company_name
    }else{
      //自付合同 也可能是非标代付
      compliance.form.has_payment=0
      compliance.form.has_invoice=1
      compliance.form.company_name=selectItem.company_name
      compliance.form.relate_contract_code=''
      compliance.form.actual_pay_companies=''
    }
    // 获取套餐详情
    getServiceDetail({contract_id:selectItem.contract_id}).then(res=>{
      if(!res.data) return 
      //非标代付合同
      if(res.data.RelationContractDetailList && res.data.RelationContractDetailList.length>0 && selectItem.contract_business_type_int==1){
        compliance.form.has_payment=1
        compliance.form.has_invoice=0
        compliance.form.relate_contract_code = res.data.RelationContractDetailList.map(it => it.ContractCode).join(',')
        compliance.form.company_name=selectItem.company_name
        compliance.form.actual_pay_companies=res.data.RelationContractDetailList.map(it => it.CompanyName).join(',')
      }
      compliance.contractTypeCheck = [compliance.form.has_payment,compliance.form.contract_type]
      let servivesTemp
      if(selectItem.contract_type_key==3){
        // 代付合同 套餐取 关联合同的套餐
        servivesTemp=res.data.RelationContractDetailList[0]?res.data.RelationContractDetailList[0].Service||[]:[]
      }else{
        servivesTemp=res.data.Service || []
      }
      if(selectItem.product_id==1){
        // 清空权益套餐
        serviceData.serviceVarietyShowQy = false
        serviceData.serviceTypeQy = 0
        serviceData.checkedServiceQy=[]
        compliance.form.services_Qy_amount = ''
        // FICC套餐
        // 小套餐
        let smallService = servivesTemp.find(item => item.ServiceTemplateId==2)
        // 是否有大套餐
        let hasBigService = servivesTemp.some(item => item.ServiceTemplateId==1)
        serviceData.serviceVarietyShow=!!smallService
        serviceData.serviceType = !!smallService?2:hasBigService?1:0
        serviceData.checkedService=servivesTemp.map(item => item.ServiceTemplateId)
        serviceData.checkedPermission=smallService?smallService.ChartPermissionIds||[]:[]
        compliance.form.services_amount = res.data.Price
      }else{
        // 清空FICC套餐
        serviceData.serviceVarietyShow = false
        serviceData.serviceType = 0
        serviceData.checkedService=[]
        compliance.form.services_amount = ''
        //权益
        // 权益大套餐
        let bigServiceQY = servivesTemp.find(item => item.FMSServiceTemplateId==11 || item.FMSServiceTemplateId==12)
        // 行业套餐 - 医药/消费/科技/智造/策略
        let smallServiceQY = servivesTemp.filter(item => [14,15,16,17,18].includes(item.FMSServiceTemplatePId))

        serviceData.serviceVarietyShowQy = (!!bigServiceQY) || (!!smallServiceQY)
        serviceData.serviceTypeQy = serviceData.qYDiaType =  !!bigServiceQY?1:!!smallServiceQY?2:0
        serviceData.checkedServiceQy=[!!bigServiceQY?10:13]

        compliance.form.services_Qy_amount = res.data.Price
        if(!!bigServiceQY){
          //权益大套餐
          serviceData.checkedPermissionQyBig = [bigServiceQY.FMSServiceTemplateId]
          serviceData.checkedPermissionQySmall = []
        }else{
          //行业套餐
          serviceData.checkedPermissionQyBig = []
          serviceData.checkedPermissionQySmall = smallServiceQY.map(item => item.FMSServiceTemplateId)
        }
      }
      serviceData.varietyDiaType='edit'
    })
    // compliance.form.product_ids = selectItem.product_id.toString()
    sellerListType.value = selectItem.product_id

    compliance.hasQYSeller=selectItem.product_id==2

    compliance.form.crm_contract_id=selectItem.contract_id
    compliance.form.start_date=selectItem.start_date
    compliance.form.end_date=selectItem.end_date
    compliance.contractValidityDate=[selectItem.start_date,selectItem.end_date]
    compliance.form.contract_amount=selectItem.price
    compliance.form.seller_id=selectItem.seller_id
    compliance.form.seller_ids=selectItem.seller_id+''
    // selectItem.contract_type_int 1-新签 2-续约 3-补充
    // compliance.form.contract_type 1-新签 2-续约 4-补充
    compliance.form.contract_type=selectItem.contract_type_int==3?4:selectItem.contract_type_int
    compliance.form.relate_contract_main_code=!compliance.form.has_payment?selectItem.relate_contract_main_code:''
    contractInfoForm.value && 
    contractInfoForm.value.validateField([
      'contract_code','company_name','contract_type','seller_ids',
      'start_date','contract_amount','relate_contract_code','actual_pay_companies'
    ])
  }

  // 合规登记-提交
  const complianceSubmit=()=>{
    contractInfoForm.value.validate(valid=>{
      if(valid){
        compliance.form.services=[]
        compliance.form.service_amount=[]
        if(serviceData.checkedServiceQy.length==0 && serviceData.checkedService.length==0){
          ElMessage.warning('请选择套餐')
          return 
        }
        let hasFICCservice=false
        let hasQYservice=false
        // FICC
        if(serviceData.checkedService.length>0){
          hasFICCservice=true
          if((!serviceData.checkedPermission || serviceData.checkedPermission.length==0) 
          && serviceData.checkedService.some(serviceId =>serviceId==2)){
            ElMessage.warning('请保存FICC小套餐品种')
            return 
          }
          serviceData.checkedService.map(serviceId=>{
            let serviceSelectItem = props.serviceItem.serviceArray.find(it=> it.service_template_id==serviceId) || {}
            // 小套餐
            if(serviceId==2){
              compliance.form.services.push({
                service_template_id:serviceSelectItem.service_template_id,
                value:'',
                chart_permission_ids:serviceData.checkedPermission?serviceData.checkedPermission.join(','):'',
                chart_permission_id:serviceSelectItem.chart_permission_id,
                title:serviceSelectItem.title
              })
            }
            else if(serviceId==3){
              compliance.form.services.push(serviceSelectItem)
            }
            else{
              compliance.form.services.push({service_template_id:serviceSelectItem.service_template_id,title:serviceSelectItem.title})
            }
          })
          // 套餐金额
          
          if(!compliance.form.services_amount){
            ElMessage.error('请填写FICC套餐金额')
            return 
          }
          if(!parseFloat(compliance.form.services_amount)){
            ElMessage.error('FICC套餐金额格式错误')
            return 
          }
          compliance.form.service_amount.push({product_id:1,service_amount:+compliance.form.services_amount})
          compliance.form.services_amount = +parseFloat(compliance.form.services_amount).toFixed(2) || 0
        }
        
        // 权益
        if(serviceData.checkedServiceQy.length>0){
          hasQYservice=true
          // 权益大套餐
          if((!serviceData.checkedPermissionQyBig || serviceData.checkedPermissionQyBig.length==0) 
          && serviceData.checkedServiceQy.some(serviceId =>serviceId==10)){
            ElMessage.warning('请保存权益大套餐类型')
            return 
          }

          // 行业套餐
          if((!serviceData.checkedPermissionQySmall || serviceData.checkedPermissionQySmall.length==0) 
          && serviceData.checkedServiceQy.some(serviceId =>serviceId==13)){
            ElMessage.warning('请保存行业套餐品种')
            return 
          }
          serviceData.checkedServiceQy.map(serviceId=>{
            let serviceSelectItem = props.serviceItem.serviceArrayQy.find(it=> it.service_template_id==serviceId)
            if(serviceSelectItem)
            compliance.form.services.push({service_template_id:serviceSelectItem.service_template_id,title:serviceSelectItem.title})
            // 权益大套餐
            if(serviceId==10){
              let subServiceItem = serviceSelectItem.children.find(it=> it.service_template_id==serviceData.checkedPermissionQyBig[0])
              compliance.form.services.push({service_template_id:subServiceItem.service_template_id,title:subServiceItem.title})
            }else if(serviceId==13){
              // 行业套餐 - 每一层都要push
              // 是否有子层被选中
              const hasSubList=[0,0,0,0,0]
              serviceData.checkedPermissionQySmall.map(serviceTemplateId=>{
                for (let i = 0; i < serviceSelectItem.children.length; i++) {
                  const element = serviceSelectItem.children[i];
                  // 最后一层 - 主客观
                  let subItem=element.children.find(it =>it.service_template_id == serviceTemplateId)
                  if(subItem){
                    compliance.form.services.push({service_template_id:subItem.service_template_id,title:subItem.title})
                    hasSubList[i]=element.service_template_id
                    break;
                  }
                }
              })
              // 中间层 - 医药、消费、科技、智造、策略
              hasSubList.map((serviceTemplateId,ind) =>{
                if(serviceTemplateId){
                  let tempItem = serviceSelectItem.children[ind]
                  compliance.form.services.push({service_template_id:tempItem.service_template_id,title:tempItem.title})
                }
              })
            }
          })
          // 套餐金额
          if(!compliance.form.services_Qy_amount){
            ElMessage.error('请填写权益套餐金额')
            return 
          }
          if(!parseFloat(compliance.form.services_Qy_amount)){
            ElMessage.error('权益套餐金额格式错误')
            return 
          }
          compliance.form.service_amount.push({product_id:2,service_amount:+compliance.form.services_Qy_amount})
          compliance.form.services_Qy_amount = +parseFloat(compliance.form.services_Qy_amount).toFixed(2) || 0
        }
        let servicesAll=0
        if(hasFICCservice&&hasQYservice){
          servicesAll = Math.round((compliance.form.services_Qy_amount+compliance.form.services_amount)*100)/100
          compliance.form.product_ids = '1,2'
        }else if(hasFICCservice){
          servicesAll = compliance.form.services_amount
          compliance.form.services_Qy_amount=''
          compliance.form.product_ids = '1'
        }else{
          servicesAll = compliance.form.services_Qy_amount
          compliance.form.services_amount=''
          compliance.form.product_ids = '2'
        }
        compliance.form.contract_amount = +parseFloat(compliance.form.contract_amount).toFixed(2)
        if(servicesAll!=compliance.form.contract_amount){
          ElMessage.error('套餐总金额不等于合同金额')
          return 
        }

        if(!compliance.form.has_payment){
          compliance.form.has_payment=0
          compliance.form.actual_pay_companies=''
        }
        // 检验合同名称或者合同有效期是否重复
        if(compliance.form.contract_register_id){
          // 编辑
          registerEdit(compliance.form).then(res=>{
            let messageHint=ElMessage.success('合规登记编辑成功')
            setTimeout(()=>{
              messageHint.close()
              emits('submitSuccess')
            },1000)
          })
        }else{
          let params=compliance.form
          if(props.supplementaryInfo.id){
            // 预登记过来的
            params={...params,contract_register_id:props.supplementaryInfo.id}
          }
          // console.log(params,'params');
          // 新增
          contractRegisterCheck({company_name:compliance.form.company_name,
            start_date:compliance.form.start_date,end_date:compliance.form.end_date,seller_ids:compliance.form.seller_ids}).then(res=>{
            if(res.data?.exist){
              // 存在给提示
              ElMessageBox.confirm('已登记过相同的合同，是否继续操作？',
              '操作提示',{
                type:'warning',
                confirmButtonText: '确定',
                cancelButtonText: '取消'
              }).then(resp=>{
                registerAdd(params).then(res=>{
                  let messageHint=ElMessage.success('合规登记成功')
                  setTimeout(()=>{
                    messageHint.close()
                    emits('submitSuccess')
                  },1000)
                })
              }).catch(()=>{})
            }else{
              registerAdd(params).then(res=>{
                let messageHint=ElMessage.success('合规登记成功')
                setTimeout(()=>{
                  messageHint.close()
                  emits('submitSuccess')
                },1000)
              })
            }
          })
        }
      }
    })
  }
  const canServiceShow=(serviceTemplateId)=>{
    return compliance.form.services.find(item => item.service_template_id == serviceTemplateId) && props.operationtype!='compliance'
  }
  // 查看套餐 - ficc
  const viewService=(serviceTemplateId)=>{
    if(!canServiceShow(serviceTemplateId)) return 
    if(serviceTemplateId==2){
      serviceData.varietyDiaShow=true
      serviceData.varietyDiaType='view'
      return 
    }
    let viewItem=compliance.form.services.find(item => item.service_template_id == serviceTemplateId)
    previewImageTitle.value = viewItem.title
    previewImage.value=viewItem.value
    serviceData.serviceShow=true
  }

  // 查看套餐 - 权益
  const viewServiceQy=(serviceTemplateId,diaType)=>{
    if(!canServiceShow(serviceTemplateId)) return 
    serviceData.varietyDiaShowQy=true
    serviceData.qYDiaType = diaType
    serviceData.varietyDiaType='view'
  }
  // 合同编号远程搜索
  const contractNoSearch=(value)=>{
    if(!value.trim()) return 
    contractNoQuery.keyword=value
    contractNoQuery.current=1
    contractNoInfo.contractNoArray=[]
    getContractSearchListFun()
  }
  const loadContractNoMore=()=>{
    if(contractNoInfo.contractNoArray.length >=contractNoInfo.contractNoTotal) return 
    contractNoQuery.current++
    getContractSearchListFun()
  }
  const getContractSearchListFun=()=>{
    contractNoInfo.contractNoLoading=true 
    getContractSearchList(contractNoQuery).then(res=>{
      contractNoInfo.contractNoArray=contractNoInfo.contractNoArray.concat(res.data.list || [])
      contractNoInfo.contractNoTotal=res.data.page.total
    }).finally(()=>{
      contractNoInfo.contractNoLoading=false
    })
  }


  // 销售选中
  const selectSeller=(value)=>{
    compliance.form.seller_ids=value+''
  }

  // 选择品种 - ficc
  const selectVariety=()=>{
    serviceData.varietyDiaType='edit'
    serviceData.varietyDiaShow=true
  }
  // 选择品种 - 权益
  const selectVarietyQy=(diaType)=>{
    serviceData.varietyDiaType='edit'
    serviceData.varietyDiaShowQy=true
    serviceData.qYDiaType = diaType
  }

  const getPermissionChecked=(list)=>{
    serviceData.checkedPermission=list
  }

  const getPermissionQYChecked=(list)=>{
    if(serviceData.qYDiaType==1) serviceData.checkedPermissionQyBig=list
    else if(serviceData.qYDiaType==2) serviceData.checkedPermissionQySmall=list
  }

  // 有效期变更触发函数
  const contractValidityDateChane=(value)=>{
    if(value){
      compliance.form.start_date=value[0]
      compliance.form.end_date=value[1]
    }else{
      compliance.form.start_date=compliance.form.end_date=''
    }
  }


  // 服务改变
  const serciveChange=(value,type,serviceType='ficc',openDia=true)=>{
    if(serviceType=='ficc'){
      if(type==2){
        serviceData.serviceVarietyShow=value
        serviceData.varietyDiaType='edit'
        serviceData.varietyDiaShow=openDia&&value
      }
      serviceData.serviceType = value?type:0
    }else{
      serviceData.serviceVarietyShowQy=value
      serviceData.varietyDiaType='edit'
      serviceData.varietyDiaShowQy=openDia&&value
      serviceData.serviceTypeQy = serviceData.qYDiaType =  value?type:0
    }
  }

  const setSupplementaryData=()=>{
    compliance.form.supplement =1
    compliance.form.company_name = props.supplementaryInfo.company_name
    compliance.form.currency_unit = props.supplementaryInfo.currency_unit
    compliance.form.start_date = props.supplementaryInfo.start_date
    compliance.form.end_date = props.supplementaryInfo.end_date
    compliance.contractValidityDate = [compliance.form.start_date,compliance.form.end_date]
    compliance.contractTypeCheck=[props.supplementaryInfo.has_payment,props.supplementaryInfo.contract_type]
    contractTypeChange(compliance.contractTypeCheck)
    serviceDataHandle(props.supplementaryInfo.services)
  }

  const setComplianceDetail=()=>{
    compliance.form.product_ids=props.detailInfo.product_ids
    compliance.form.contract_register_id=props.detailInfo.contract_register_id
    compliance.form.crm_contract_id=props.detailInfo.crm_contract_id
    compliance.form.contract_code=props.detailInfo.contract_code
    compliance.form.company_name=props.detailInfo.company_name
    compliance.form.currency_unit=props.detailInfo.currency_unit
    compliance.form.seller_ids=props.detailInfo.seller_ids
    compliance.form.seller_id=props.detailInfo.seller_id || props.detailInfo.rai_seller_id
    compliance.form.contract_status=props.detailInfo.contract_status
    compliance.form.start_date=props.detailInfo.start_date
    compliance.form.end_date=props.detailInfo.end_date
    compliance.form.contract_amount=props.detailInfo.contract_amount
    compliance.form.contract_type=props.detailInfo.contract_type
    compliance.form.has_payment=props.detailInfo.has_payment
    compliance.form.has_invoice=props.detailInfo.has_invoice
    compliance.form.actual_pay_companies=props.detailInfo.actual_pay_companies
    compliance.form.relate_contract_code=props.detailInfo.relate_contract_code
    compliance.form.relate_contract_main_code=props.detailInfo.relate_contract_main_code
    compliance.form.sign_date=props.detailInfo.sign_date
    compliance.form.agreed_pay_time=props.detailInfo.agreed_pay_time
    compliance.form.service_remark=props.detailInfo.service_remark
    compliance.form.remark=props.detailInfo.remark
    compliance.form.contract_source=props.detailInfo.contract_source
    // 有效期回显 
    compliance.contractValidityDate=[compliance.form.start_date,compliance.form.end_date]
    // 合同类型回显
    compliance.contractTypeCheck = [compliance.form.has_payment,compliance.form.contract_type]
    // 销售显示
    sellerListType.value=props.detailInfo.sellerListType
    if(sellerListType.value==3){
      cascaderSelectSeller.value = compliance.form.seller_ids.split(',').map(item => +item)
    }
    
    compliance.hasQYSeller = props.detailInfo.rai_seller_id?true:false
    
    // 套餐金额
    compliance.form.services_amount = props.detailInfo.service_amount_list.find(it => it.product_id==1)?
    props.detailInfo.service_amount_list.find(it => it.product_id==1).service_amount:0
    compliance.form.services_Qy_amount = props.detailInfo.service_amount_list.find(it => it.product_id==2)?
    props.detailInfo.service_amount_list.find(it => it.product_id==2).service_amount:0
    serviceDataHandle(props.detailInfo.services)
  }
  // 回显套餐数据
  const serviceDataHandle=(services)=>{
    services.map(item =>{
      if(item.service_template_id==2){
        // ficc小套餐
        compliance.form.services.push({
          service_template_id:item.service_template_id,
          value:item.value,
          chart_permission_ids:item.chart_permission_ids,
          chart_permission_id:item.chart_permission_id,
          title:item.title
        })
        serviceData.checkedPermission=item.chart_permission_ids.split(',')
      }else if(item.service_template_id==11 || item.service_template_id==12){
        // 权益大套餐
        serviceData.checkedPermissionQyBig = [item.service_template_id]
        compliance.form.services.push(item)
      }else if([19,20,21,22,23,24,25,26,27].includes(item.service_template_id)){
        // 行业套餐
        serviceData.checkedPermissionQySmall.push(item.service_template_id)
        compliance.form.services.push(item)
      }else{
        compliance.form.services.push(item)
      }
    })
    serviceData.checkedService=services.map(item => {
      if(item.product_id==1){
        let serviceId=item.service_template_id
        // 大套餐或者小套餐
        if(serviceId==1 || serviceId==2) serciveChange(true,serviceId,'ficc',false)
        return serviceId
      }
    }).filter(Boolean)
    serviceData.checkedServiceQy=services.map(item => {
      if(item.product_id==2){
        let serviceId=item.service_template_id
        // 权益大套餐或者行业套餐
        if(serviceId==10 || serviceId==13) serciveChange(true,serviceId==10?1:2,'qy',false)
        return serviceId
      }
    }).filter(Boolean)
  }

  // --------------------------------------开始
  defineExpose({
    complianceSubmit
  })
</script>

<template>
    <div id="contractProgress-compliance">
      <div class="info-row" id="contract-info-container">
        <div class="info-row-title">合同信息</div>
        <div style="margin: 0px 42px 0 62px;">
          <el-form :model="compliance.form" inline ref="contractInfoForm" label-width="130" 
          :disabled="operationtype!='compliance'"
          :rules="compliance.rules" class="contractInfo-form">
            <el-form-item label="合同来源" prop="contract_source" >
              <el-select v-model="compliance.form.contract_source" :disabled="compliance.form.supplement!=0"
              placeholder="请选择合同来源" @change="contractSourceChange">
                <el-option :label="item" :value="index" 
                v-for="(item,index) in contractSourceArray" :key="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="合同编号" prop="contract_code" id="selectContract">
              <el-input v-model="compliance.form.contract_code" placeholder="请输入合同编号"
              v-if="compliance.form.contract_source==0" >
                <template #prefix v-if="compliance.form.has_payment==1">
                  <span>{{ compliance.form.has_invoice==1?'代付方':'实际使用方' }}</span>
                </template>
              </el-input>
              <scrollableSelect :loadMoreMethod="loadContractNoMore" v-model="compliance.form.contract_code" placeholder="请搜索合同编号" v-else
              :searchMethod="contractNoSearch" @change="selectContractNo" useLoading :isLoading="contractNoInfo.contractNoLoading" 
              >
                <template #prefix v-if="compliance.form.has_payment==1">
                  <span>{{ compliance.form.has_invoice==1?'代付方':'实际使用方' }}</span>
                </template>
                <el-option :label="item.contract_code" :value="item.contract_code" v-for="item in contractNoInfo.contractNoArray" :key="item.contract_id"></el-option>
              </scrollableSelect>
            </el-form-item>
            <el-form-item label="客户名称" prop="company_name">
              <el-input v-model="compliance.form.company_name" 
              placeholder="请输入客户名称（实际使用方）"  />
            </el-form-item>
            <el-form-item label="销售" prop="seller_ids">
              <el-cascader v-if="sellerListType==3" filterable style="min-width: 320px;width: 15vw;"
              :options="sellerData.all_list" placeholder="请选择销售" @change="sellerChange" 
              :show-all-levels="false" v-model="cascaderSelectSeller" 
              :clearable="false" :props="{multiple:true,label:'seller_name',value:'seller_id',children:'child'}"
              key="seller" >
              </el-cascader>
              <el-select v-else-if="!sellerListType" placeholder="请选择销售" filterable  >
                <el-option :label="item" :value="item" v-for="item in []" :key="item"></el-option>
              </el-select>
              <el-cascader v-else filterable style="min-width: 320px;width: 15vw;"
              :options="sellerListType==1?onlyFICCSellerData:onlyQYSellerData" @change="selectSeller"
              placeholder="请选择销售" :show-all-levels="false" v-model="compliance.form.seller_id" 
              :clearable="false" :props="{multiple:false,label:'seller_name',value:'seller_id',children:'child',emitPath:false}"
              key="seller-single" >
              </el-cascader>
            </el-form-item>
            <el-form-item label="合同金额" id="contractInfo-contractAmount"
            prop="contract_amount">
              <el-input v-model.trim="compliance.form.contract_amount"
              placeholder="请输入合同金额"  />
              <el-select v-model="compliance.form.currency_unit" placeholder="请选择货币类型" 
              style="margin-left: 20px;" :disabled="compliance.form.supplement!=0">
                <el-option v-for="item in currencyList" :key="item.code" :label="item.name" :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="合同有效期" 
            prop="start_date">
              <el-date-picker type="daterange" 
              v-model="compliance.contractValidityDate" @change="contractValidityDateChane"
              start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD"
              :clearable="false">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="合同类型" prop="contract_type" id="contractInfo-contractType">
              <el-cascader :options="contractTypeArray" placeholder="请选择合同类型" @change="contractTypeChange"
              v-model="compliance.contractTypeCheck" :clearable="false" key="contractType">
              </el-cascader>
            </el-form-item>
            <el-form-item label="关联主合同" prop="relate_contract_main_code" 
            v-if="compliance.form.contract_type==4">
              <el-input v-model="compliance.form.relate_contract_main_code" 
              placeholder="请输入关联主合同" />
            </el-form-item>
            <el-form-item label="合同所属方" prop="has_invoice"
            :rules="{required:true,message:'合同所属方不能为空',trigger:'blur'}"
            v-if="compliance.form.has_payment==1">
              <el-select v-model="compliance.form.has_invoice" 
                placeholder="请选择合同所属方" >
                  <el-option :label="item" :value="index" v-for="(item,index) in contractOwnereArray" :key="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="代付方" prop="actual_pay_companies" class="actual_pay_companies"
            :rules="compliance.form.contract_source==0?{required:true,message:'代付方不能为空',trigger:'blur'}:{required:false}"
            v-if="compliance.form.has_payment==1">
              <div v-overflowTooltip="'#overflow-input'">
                <el-tooltip placement="top" :content="compliance.form.actual_pay_companies" >
                  <el-input v-model="compliance.form.actual_pay_companies"
                  placeholder="请输入代付方信息" id="overflow-input" />
                </el-tooltip>
              </div>
            </el-form-item>
            <el-form-item :label="compliance.form.has_invoice==1?'关联客户合同':'关联代付合同'" prop="relate_contract_code" v-if="compliance.form.has_payment">
              <el-input v-model="compliance.form.relate_contract_code" 
              :placeholder="compliance.form.has_invoice==1?'请输入实际使用方合同编号':'请输入代付合同编号'" />
            </el-form-item>
            <el-form-item label="合同状态" prop="contract_status">
              <el-select v-model="compliance.form.contract_status" 
              placeholder="请选择合同状态" >
                <el-option :label="item.label" :value="item.id" v-for="item in contractStatusArray" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="签订日" prop="sign_date" >
              <el-date-picker v-model="compliance.form.sign_date" 
              placeholder="请选择签订日" value-format="YYYY-MM-DD"
              :clearable="false">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="约定付款时间" prop="agreed_pay_time">
              <el-input v-model="compliance.form.agreed_pay_time" 
              placeholder="请输入约定付款时间" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="info-row">
        <div class="info-row-title" >套餐信息</div>
        <div class="info-row-services">
          <div class="info-row-services-header" id="info-row-services-header">
            <span>FICC套餐</span>
            <el-input v-model="compliance.form.services_amount" :disabled="operationtype!='compliance'"
            placeholder="请输入套餐金额" style="width: 200px;" />
          </div>
            <el-checkbox-group :disabled="operationtype!='compliance'"
          v-model="serviceData.checkedService" class="info-service-box" id="service-information">
            <!-- 大套餐 -->
            <el-checkbox :label="serviceItem.serviceArray[0]?.service_template_id" @change="(e) => serciveChange(e,1)" 
              :class="{'viewService':canServiceShow(serviceItem.serviceArray[0]?.service_template_id)}"
            :disabled="serviceData.serviceType==2" @click="viewService(serviceItem.serviceArray[0]?.service_template_id)">
              {{serviceItem.serviceArray[0]?.title}}
            </el-checkbox>
            <!-- 小套餐 -->
            <div class="service-small">
              <el-checkbox :label="serviceItem.serviceArray[1]?.service_template_id" style="margin-right: 0;"
              @change="(e) => serciveChange(e,2)" 
                :class="{'viewService':canServiceShow(serviceItem.serviceArray[1]?.service_template_id)}"
                :disabled="serviceData.serviceType==1" @click="viewService(serviceItem.serviceArray[1]?.service_template_id)">
                {{serviceItem.serviceArray[1]?.title}}
              </el-checkbox>
              <span v-if="(serviceData.serviceVarietyShow&&operationtype=='compliance')" 
              @click="selectVariety" class="select-variety">选择品种</span>
            </div>
            <!-- 市场策略 -->
            <el-checkbox :label="serviceItem.serviceArray[2]?.service_template_id"
            @click="viewService(serviceItem.serviceArray[2]?.service_template_id)"
            :class="{'viewService':canServiceShow(serviceItem.serviceArray[2]?.service_template_id)}">
            {{serviceItem.serviceArray[2]?.title}}
            </el-checkbox>
            <!-- 财富管理类似没有详情的套餐 -->
            <el-checkbox v-for="item in serviceItem.serviceArray.slice(3)" :label="item.service_template_id">
              {{item.title}}
            </el-checkbox>
          </el-checkbox-group>
        </div>
        <div class="info-row-services" v-show="compliance.hasQYSeller!==false">
          <div class="info-row-services-header" id="info-row-services-header">
            <span>权益套餐</span>
            <el-input v-model="compliance.form.services_Qy_amount" :disabled="operationtype!='compliance'"
            placeholder="请输入套餐金额" style="width: 200px;" />
          </div>
            <el-checkbox-group :disabled="operationtype!='compliance'"
          v-model="serviceData.checkedServiceQy" class="info-service-box" id="service-information">
            <!-- 权益大套餐、行业套餐 -->
            <div class="service-small" v-for="(item,index) in [1,2]" :key="item">
              <el-checkbox :label="serviceItem.serviceArrayQy[index]?.service_template_id" style="margin-right: 0;"
              @change="(e) => serciveChange(e,item,'qy')" 
                :class="{'viewService':canServiceShow(serviceItem.serviceArrayQy[index]?.service_template_id)}"
                :disabled="serviceData.serviceTypeQy!=0 && serviceData.serviceTypeQy != item" 
                @click="viewServiceQy(serviceItem.serviceArrayQy[index]?.service_template_id,item)">
                {{serviceItem.serviceArrayQy[index]?.title}}
              </el-checkbox>
              <span v-if="(serviceData.serviceVarietyShowQy&&serviceData.qYDiaType==item&&operationtype=='compliance')" 
              @click="selectVarietyQy(item)" class="select-variety">选择品种</span>
            </div>
            <!-- 非行业套餐 -->
            <el-checkbox v-for="item in serviceItem.serviceArrayQy.slice(2)" :label="item.service_template_id">
              {{item.title}}
            </el-checkbox>
          </el-checkbox-group>
        </div>
        <div class="remark info-service-remark">
          <span style="white-space: nowrap;font-size: 14px;margin-right: 20px;">套餐备注</span>
          <el-input style="flex-grow: 1;" :disabled="operationtype!='compliance'"
              v-model="compliance.form.service_remark" placeholder="请输入备注"
            />
        </div>
      </div>
      <div class="info-row">
        <div class="info-row-title">备注</div>
        <div class="info-row-remark">
          <span style="white-space: nowrap;font-size: 14px;margin-right: 20px;">备注</span>
          <el-input style="flex-grow: 1;" :disabled="operationtype!='compliance'"
            v-model="compliance.form.remark" placeholder="请输入备注"
          />
        </div>
      </div>
      <!-- 小套餐选择品种弹窗 -->
      <permission-dia v-model:visible="serviceData.varietyDiaShow" :type="serviceData.varietyDiaType"
      @selectFinish="getPermissionChecked" :hasCheckedPermission="serviceData.checkedPermission"></permission-dia>
      <!-- 权益大套餐、行业套餐选择品种弹窗 -->
      <permission-qy-dia v-model:visible="serviceData.varietyDiaShowQy" :type="serviceData.varietyDiaType" 
      @selectFinish="getPermissionQYChecked" :serviceType="serviceData.qYDiaType"
      :permissionData="serviceData.qYDiaType==1?serviceItem.serviceArrayQy[0]?.children:serviceItem.serviceArrayQy[1]?.children"
      :hasCheckedPermission="serviceData.qYDiaType==1?serviceData.checkedPermissionQyBig:serviceData.checkedPermissionQySmall"></permission-qy-dia>
      <!-- 查看套餐弹窗 -->
      <el-dialog v-model="serviceData.serviceShow" style="min-width: 800px;" title="" width="70vw" top="5vh">
        <template #header>
          <div style="text-align: center;">{{previewImageTitle}}</div>
        </template>
        <img style="width: 100%; display: block; margin: 0 auto 20px auto" 
        :src="previewImage" />
        <div style="text-align: center; margin: 30px 0 10px">
          <el-button type="primary" @click="serviceData.serviceShow=false">知道了</el-button>
        </div>
      </el-dialog>
    </div>
</template>
  
<style lang="scss" scoped>

</style>
<style lang="scss">
#contractProgress-compliance{
  #contract-info-container{
    .el-select,.el-date-editor,.actual_pay_companies{
      .el-input__wrapper,.el-input{
        min-width: 320px;
        width: 15vw;
      }
    }
    .el-form-item{
      .el-form-item__content{
        min-width: 320px;
        width: 15vw;
        flex-wrap: nowrap;
      }
    }
  }
  #contractInfo-contractAmount{
    .el-input__wrapper,.el-input{
      min-width: 200px;
      flex-grow: 1;
    }
    .el-select{
      .el-input__wrapper,.el-input{
        min-width: 100px;
        width: 100px;
      }
    }
  }
  #contractInfo-contractType{
    display: flex;
    .el-cascader{
      min-width: 180px;
      flex-grow: 1;
    }
    .el-checkbox{
      min-width: 120px;
      width: 120px;
    }
  }
  #info-row-services-header{
    .el-input__wrapper{
      height: 30px;
    }
  }
  #service-information{
    .el-checkbox{
      margin-right: 40px;
    }
  }
  .viewService{
    .el-checkbox__label{
      cursor: pointer;
      color: $themeColor;
    }
  }
}
</style>