<template>
  <div class="addconstract-container">
    <el-form ref="form" :model="formData" label-position="left" :rules="formRule" label-width="110px">
      <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="customeName" style="width: 50%">
              <!-- <el-input v-model="formData.customeName" placeholder="请输入名称" style="width: 350px"></el-input> -->
              <el-autocomplete
                v-model="formData.customeName"
                :fetch-suggestions="querySearchAsyncCustome"
                placeholder="请输入或者搜索客户名称"
                @select="handleSelectCustome"
                @blur="handleCustomeInputChange"
                style="width: 50%"
              ></el-autocomplete>
            </el-form-item>
            <el-form-item label="社会信用码" prop="customeXYM" style="width: 50%">
              <el-input v-model="formData.customeXYM" 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="formData.province" :city="formData.city" 
                :province-source="province_sorce"
                :city-source="city_sorce"
                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.customeCz" placeholder="请输入传真" style="width: 350px"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="customeTel" style="width: 50%">
              <el-input v-model="formData.customeTel" 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>{{ temContractCode }}</span>
            </el-form-item>
            <el-form-item label="合同归属" style="width: 50%">
              <span>{{ RoleType === "ficc_seller" ? "FICC" : "权益" }}</span>
            </el-form-item>
          </div>
          <el-form-item label="合同类型" prop="constractType" class="border-top" v-if="!raiCompanyType && !raiCompanyStatus">
            <el-radio-group v-model="formData.constractType">
              <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="time" style="width: 50%">
              <el-date-picker 
                v-model="formData.time" 
                type="daterange" 
                value-format="yyyy-MM-dd" 
                range-separator="至" 
                start-placeholder="开始日期" 
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                :disabled="timeDisable"> 
              </el-date-picker>
            </el-form-item>
            <span style="line-height: 40px">{{ formData.time | formateYear }}</span>
          </div>

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

          <div class="flex border-top">
            <el-form-item  :label="raiCompanyType ? '实际付款金额' : '优惠后金额'"  prop="price2" style="width: 50%">
              <el-input v-model="formData.price2" @focus="handlePriceBoxFocus('price2')" @blur="handlePriceBoxBlur('price2')" 
              :placeholder="raiCompanyType ? '请输入实际付款金额(优惠后)' : '请输入优惠后金额'"
              style="width: 220px"></el-input>
            </el-form-item>
            <span style="line-height: 40px">{{ formData.price2 | 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.constractType"
            @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;font-size:14px">补充内容（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>
        <!-- <div style="text-align: center; margin-top: 40px; margin-bottom: 20px">
          <el-button type="primary" plain style="width: 145px" @click="handleSubmit('预览')">预览</el-button>
          <el-button type="primary" @click="handleSubmit('存草稿')" style="width: 145px">存草稿</el-button>
          <el-button type="primary" @click="handleSubmit('提交')" style="width: 145px">提交</el-button>
        </div> -->
      </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>
        <div style="text-align: center; margin-top: 40px; margin-bottom: 20px">
          <el-button type="primary" plain style="width: 145px" @click="handleSubmit('预览')">预览</el-button>
          <el-button type="primary" @click="handleSubmit('存草稿')" style="width: 145px">存草稿</el-button>
          <el-button type="primary" @click="handleSubmit('提交')" style="width: 145px">提交</el-button>
        </div>
      </section>
    </el-form>

    <!-- 套餐 -->
    <ServiceDialog ref="ServiceDialog" :contractType="formData.constractType" :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: "addConstract",
  components: {
    ServiceDialog,
    QyServiceTable,
    FiccServiceTable,
  },
  computed: {
    pickerOptions(){
      let obj={disabledDate() {return false}}
      if(this.cusLastcontract){
        if(this.formData.constractType==='续约合同'&&this.RoleType==='ficc_seller'){
          // ficc 起始日期为权限中最大的时间
          this.formData.time=[]
          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(this.formData.constractType==='补充协议'){
          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.time=[today,endDate]
          this.timeDisable=true
          obj={disabledDate() {return true}}
        }else{
          this.timeDisable=false
        }
      }
      
      return obj
    },
  },
  filters: {
    // 金额转中文大写
    digitUppercase(n) {
      if (n) {
        n=n.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(/^整$/, "零元整")
        );
      }
    },

    //计算多少年 X年X个月X天
    formateYear(e) {
      if (!e) return;
      if (e[0]) {
        return `有效期为${CalculationDate(e[0],e[1])}`
      }
    },
  },
  watch: {
    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:{},
      timeDisable:false,
      cusLastcontract:null,

      temContractCode: null, //临时生成的合同编号
      RoleType: localStorage.getItem("Role") || "",
      radio: "2", //是否有补充内容 1有 2 无
      formData: {
        constractType: null, //合同类型
        time: [],
        price: "",
        price2: "",
        payRemark: "",
        customeName: "",
        customeXYM: "",
        customeCz: "",
        customeTel: "",
        postCode: "",
        province: "",
        city: "",
        address: "",
        remark: "",
        sellerRemark:'',
        PayChannel:['无']
      },
      formRule: {
        constractType: [{ required: true, message: "请选择合同类型", trigger: "change" }],
        time: [{ required: true, message: "请选择有效期限", trigger: "change" }],
        price: [
          { 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" }],
        customeName: [{ required: true, message: "请填写名称", trigger: "blur" }],
        customeXYM: [{ required: true, message: "请填写信用码", trigger: "blur" }],
        province: [{ required: true, message: "请选择地址", trigger: "change" }],
        remark: [{ required: false, message: "请填写补充说明", trigger: "blur" }],
        PayChannel:[{ required: true, message: "请填写付款方", trigger: "change" }],
        customeTel:[{ required: true, message: "请填写电话", trigger: "change" }],
        address:[{ required: true, message: "请填写详细地址", trigger: "change" }],
      },
      ficcServiceData: [], //ficc服务内容
      qyServiceData: [], //权益服务内容
      serviceShow: false,
      serviceCon: {}, //选择的服务项 查看报价单/选择品种
      selectServiceData: [],
      editValue: {}, //修改小套餐的value
      PayChannelOptions:[],//搜索出付款方列表

      raiCompanyType: false,// 是否是权益客户类型
      raiCompanyStatus: false// 权益客户状态
    };
  },
  created() {
    this.createTemContractCode();
    this.getServiceList();
    // 初始化一次 搜索付款方选择列表
    this.querySearchAsyncPayChannel('','init')
  },
  methods: {
    // 社会信用码变更
    async getContractByCode(){
      this.contractTypeDisable1=false
      this.contractTypeDisable2=false
      this.contractTypeDisable3=false
      if(!this.formData.customeXYM) return
      const res=await contractInterface.getContractTypeByCode({CreditCode:this.formData.customeXYM})
      if(res.Ret==200){
        let customeId=res.Data.Item&&res.Data.Item.CompanyId
        if(customeId){
          const res2=await customInterence.applyTurnContractType({CompanyId:customeId}) 
          this.formData.constractType=res2.Data.ContractType
          if(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.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(){
      // 将付款方初始化为客户名称
      // const flag=this.formData.PayChannel.includes(this.formData.customeName)
      // if(!flag){
      //   this.formData.PayChannel.push(this.formData.customeName)
      // }
    },

    // 搜索付款渠道
    // 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 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.customeXYM=res.Data.Item.CreditCode
        this.formData.province=res.Data.Item.Province
        this.formData.city=res.Data.Item.City
        this.raiCompanyType = res.Data.RaiItem && res.Data.RaiItem.ProductName == '权益'
        this.raiCompanyStatus = res.Data.RaiItem && res.Data.RaiItem.Status.includes('X类试用')
        console.log( this.raiCompanyType);
        
      }
      // 获取以前的合同自动 填充部分信息
      let res4=await contractInterface.getHistoryContract({CompanyId:item.CompanyId})
      if(res4.Ret===200){
        this.formData.address=res4.Data.Address||''
        this.formData.customeCz=res4.Data.Fax||''
        this.formData.customeTel=res4.Data.Phone||''
        this.formData.postCode=res4.Data.Postcode||''
      }
      // 更新合同类型
      let res2=await customInterence.applyTurnContractType({CompanyId:item.CompanyId})
      if(res2.Ret===200){
        this.formData.constractType=res2.Data.ContractType
        if(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.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.constractType==='补充协议') return true
      let start = new Date(this.formData.time[0]).getTime();
      let end = new Date(this.formData.time[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.price2) > Number(this.formData.price)) {
        this.$message.warning("优惠后金额不得大于合同金额");
        return false;
      } else {
        return true;
      }
    },

    // 判断小套餐中是否选择品种/新增的行是否有数据
    validateService(e,data) {
      if(!e.Value){
        this.$message.warning("请保存小套餐");
        return false
      }
      //判断品种列是否有值
      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.constractType!=='补充协议') {
        this.$message.warning("至少选择一个品种");
        return false;
      }

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

      return true;
    },

    // 生成临时的合同编号
    createTemContractCode() {
      let time = new Date();
      let year = time.getFullYear();
      let month = time.getMonth() + 1 < 10 ? "0" + (time.getMonth() + 1) : time.getMonth() + 1;
      let day = time.getDate() < 10 ? "0" + time.getDate() : time.getDate();
      let timeStr = `${year}${month}${day}`;
      let random = parseInt(Math.random() * 1000);
      if (random < 10) {
        random = `00${random}`;
      }
      if (random < 100) {
        random = `0${random}`;
      }
      let typeStr = this.RoleType === "ficc_seller" ? "FICC" : "EQ";
      this.temContractCode = `HZ${typeStr}${timeStr}${random}`;
    },

    //获取服务套餐模板数据
    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;
          }
        }
      });
    },

    //显示服务内容弹窗
    handleShowService(e) {
      this.serviceCon = e;
      this.serviceShow = true;
    },

    //关闭服务内容弹窗
    serviceClose() {
      this.serviceShow = false;
    },

    //选地地区时 选则的省份改变重置city为空
    provinceChange(e){
      this.formData.province =e.value=='省'?'':e.value;
      // this.formData.city=''
    },

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

    //小套餐点击保存 更新数据
    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.$refs.FiccServiceTable.tableData.forEach(item=>{
      //   if(item.selected){
      //     this.selectServiceData.push(item)
      //   }
      // })
      // this.selectServiceData.forEach((item) => {
      //   if (item.ServiceTemplateId === e.ServiceTemplateId) {
      //     item.Value = e.Value;
      //   }
      // });
    },

    // 预览/存草稿/提交 操作
    handleSubmit:_.debounce(function(type){
      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) {
                  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 == 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,item.Detail.slice(1));
            }
          });
          if (!flag) return;


          let params = {
            ContractType: this.formData.constractType,
            ContractBusinessType:"业务合同",
            StartDate: this.formData.time[0],
            EndDate: this.formData.time[1],
            OriginalPrice: Number(this.formData.price.replace(/,/g,'')),
            Price: Number(this.formData.price2.replace(/,/g,'')),
            PayRemark: this.formData.payRemark,
            CompanyName: this.formData.customeName,
            CreditCode: this.formData.customeXYM,
            Province: this.formData.province,
            City: this.formData.city,
            Address: this.formData.address,
            Fax: this.formData.customeCz,
            Phone: this.formData.customeTel,
            Postcode: this.formData.postCode,
            Remark: this.formData.remark,
            SellerRemark:this.formData.sellerRemark,
            PayChannel:this.formData.PayChannel.join(','),
            TemplateId: this.RoleType === "ficc_seller" ? 1 : 2,
            Service: temarr,
            IsAudit: type === "提交" ? true : false,
          };

          // 判断套餐权限
          if(this.cusLastcontract&&!this.handleValidate(params)) return
          
          if(type==='预览'){
            this.handlePreview(params)
          }else{
            this.handleSave(params)
          }
        }else{
          this.$message.warning('请完善必填项')
        }
      })
    },200),

    // 判断套餐权限
    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
              }
            })
          }

          // 市场策略
          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.time[0]).getTime()//选择的开始时间
        const time2=new Date(this.formData.time[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
    },

    //前去预览
    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");
        }
      });
    },

    //保存
    handleSave(params) {
      contractInterface.addContract(params).then((res) => {
        if (res.Ret === 200) {
          this.$router.go(-1);
        }
      });
    },

    // 金额输入框获取焦点
    handlePriceBoxFocus(key){
      let val=this.formData[key]
      val=val.replace(/,/g,'')
      this.formData[key]=val
    },
    // 金额输入框获失去焦点
    handlePriceBoxBlur(key){
      let str=this.formData[key]
      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;
}
.addconstract-container .el-checkbox__label {
  font-size: 14px !important;
}
.el-form-item {
  margin-bottom: 30px;
}
.addconstract-container .section-container .el-textarea__inner::placeholder{
  color: #999;
}
.addconstract-container .section-container .el-input__inner::placeholder{
  color: #999;
}
</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 30px;
  margin-bottom: 20px;
  .section-title {
    margin-bottom: 30px;
  }
  .border-top {
    padding-top: 30px;
    border-top: 1px solid #dcdfe6;
  }
}
</style>
