<template>
  <div class="contractdetail-dc flex">
    <el-form :model="formData" label-position="left" :rules="formRule" label-width="110px" disabled style="width: 80%">
      <section class="section">
        <h2 class="section-title">客户信息</h2>
        <div class="section-container">
          <div class="flex border-top" style="padding-top: 30px">
            <el-form-item label="代付方" prop="CompanyName" style="width: 50%">
              <el-input v-model="formData.CompanyName" placeholder="请输入名称" style="width: 350px"></el-input>
            </el-form-item>
            <el-form-item label="社会信用码" prop="CreditCode" style="width: 50%">
              <el-input v-model="formData.CreditCode" placeholder="请输入社会信用码" style="width: 350px"></el-input>
            </el-form-item>
          </div>
          <div class="flex border-top" style="padding-top: 30px">
            <el-form-item label="公司地址" prop="Province" style="width: 50%">
              <el-input :value="formData.Province + formData.City" disabled style="width: 350px"></el-input>
            </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="Fax" style="width: 50%">
              <el-input v-model="formData.Fax" placeholder="请输入传真" style="width: 350px"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="Phone" style="width: 50%">
              <el-input v-model="formData.Phone" placeholder="请输入电话" style="width: 350px"></el-input>
            </el-form-item>
          </div>
          <div class="flex border-top" style="padding-top: 30px">
            <el-form-item label="邮编" prop="Postcode" style="width: 50%">
              <el-input v-model="formData.Postcode" placeholder="请输入邮编" style="width: 350px"></el-input>
            </el-form-item>
            <el-form-item label="代付金额" prop="OriginalPrice" style="width: 50%">
              <el-input :value="formData.OriginalPrice|formatPrice" placeholder="请输入金额" style="width: 350px"></el-input>
              <span style="line-height: 40px;margin-left:20px">{{ formData.OriginalPrice | digitUppercase }}</span>
            </el-form-item>
          </div>
          <div class="border-top">
            <el-form-item label="付款方式说明" prop="PayRemark">
              <el-input type="textarea" v-model="formData.PayRemark" placeholder="请输入付款方式说明（请参考以下说明模板填写，请勿填写现金/转账等支付形式）" style="width: 80%"></el-input>
            </el-form-item>
          </div>
        </div>
      </section>

      <section class="section" v-if="relationContractData">
        <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>{{ relationContractData.ContractCode }}</span>
            </el-form-item>
            <el-form-item label="合同归属" style="width: 50%">
              <span>{{ relationContractData.ProductId === 1 ? "ficc" : "权益" }}</span>
            </el-form-item>
          </div>
          <el-form-item label="合同类型" class="border-top">
            <el-radio-group v-model="relationContractData.ContractType">
              <div style="display: flex">
                <div style="margin-right: 10px">
                  <el-radio label="新签合同" disabled>新签合同</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>续约合同</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>补充协议</el-radio>
                </div>
              </div>
            </el-radio-group>
          </el-form-item>
          <div class="flex border-top" v-if="relationContractData.timeRange">
            <el-form-item label="合同期限" style="width: 50%">
              <el-date-picker disabled v-model="relationContractData.timeRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>
            </el-form-item>
            <span style="line-height: 40px">{{ relationContractData.timeRange | formateYear }}</span>
          </div>

          <div class="flex border-top">
            <el-form-item label="合同金额" style="width: 50%">
              <el-input disabled :value="relationContractData.OriginalPrice|formatPrice" placeholder="请输入合同金额" style="width: 220px"></el-input>
            </el-form-item>
            <span style="line-height: 40px">{{ relationContractData.OriginalPrice | digitUppercase }}</span>
          </div>

          <div class="flex border-top">
            <el-form-item label="优惠后金额" style="width: 50%">
              <el-input disabled :value="relationContractData.Price|formatPrice" placeholder="请输入优惠后金额" style="width: 220px"></el-input>
            </el-form-item>
            <span style="line-height: 40px">{{ relationContractData.Price | digitUppercase }}</span>
          </div>

          <el-form-item label="付款方式说明" class="border-top">
            <el-input
              type="textarea"
              disabled
              v-model="relationContractData.PayRemark"
              placeholder="请输入付款方式说明（请参考以下说明模板填写，请勿填写现金/转账等支付形式）"
              style="width: 80%"
            ></el-input>
          </el-form-item>
          <el-form-item label="付款方" class="border-top">
            <el-input
              type="textarea"
              disabled
              v-model="relationContractData.PayChannel"
              placeholder="代付，请填写代付的券商名称或期货公司名称；非代付，请填写无。（请勿填写现金/转账等支付形式）"
              style="width: 80%"
            ></el-input>
          </el-form-item>
        </div>
      </section>

      <section class="section" v-if="relationContractData">
        <h2 class="section-title">服务内容</h2>
          <div class="section-container">
            <!-- ficc 服务内容表格 -->
            <FiccServiceTable
              :canEdit="false"
              :serviceData="ficcServiceData"
              :hasSercive="relationContractData.Service"
              @handleShowService="handleShowService"
              v-if="relationContractData.ProductId === 1 && ficcServiceData"
            ></FiccServiceTable>

            <!-- 权益 服务内容表格 -->
            <QyServiceTable
              :canEdit="false"
              :serviceData="qyServiceData"
              :hasSercive="relationContractData.Service"
              @handleShowService="handleShowService"
              v-if="relationContractData.ProductId === 2 && qyServiceData"
            ></QyServiceTable>
          </div>
          <p style="margin-top: 30px; margin-bottom: 20px">补充内容（eg额外赠送、路演次数规定）</p>
          <el-radio :value="relationContractData.Remark?'1':'2'" label="2" disabled>无</el-radio>
          <el-radio :value="relationContractData.Remark?'1':'2'" label="1" disabled>有</el-radio>
          <el-input v-if="relationContractData.Remark" disabled type="textarea" v-model="relationContractData.Remark" rows="5" placeholder="请输入内容" style="margin: 20px 0; display: block; box-sizing: border-box"></el-input>
      </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="display: flex; justify-content: space-between">
        <el-button type="primary" style="width: 45%" @click="handleGoEdit" v-if="showEdit">编辑</el-button>
        <el-button type="primary" plain :style="{width: showEdit?'45%':'100%'}" @click="handleGoPreview">预览</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>
    <!-- 查看报价单弹窗 -->
    <el-dialog v-dialogDrag :visible.sync="serviceShow" width="60%" custom-class="self-dialog-c" :modal-append-to-body="false" @close="serviceShow=false" :show-close="false">
      <h2 class="title" style="text-align: center; color: #000">{{ this.RoleType == 'ficc_seller'? serviceCon.Title : serviceCon.showTitle }}</h2>
      <img class="img" style="width: 100%; display: block; margin: 20px auto" 
      :src="this.RoleType == 'ficc_seller'? serviceCon.Value : serviceCon.showValue"/>
      <div style="text-align: center; margin-bottom: 30px">
        <el-button type="primary" @click="serviceShow=false">知道了</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { contractInterface } from "@/api/api.js";
import QyServiceTable from "./components/QyServiceTable"; //权益服务内容表格组件
import FiccServiceTable from "./components/FiccServiceTable"; //ficc服务内容表格组件
import { CalculationDate } from "@/utils/CalculationDate";
export default {
  name:"contractdetaildc",
  components: {
    QyServiceTable,
    FiccServiceTable,
  },
  filters: {
    formatPrice(str){
      if(!str) return ''
      str=str.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
      }
      return num1.replace(/(?!^)(?=(\d{3})+$)/g, ',')+num2
    },
    // 金额转中文大写
    digitUppercase(n) {
      if(!n) return ''
      let fraction = ["角", "分"];
      let digit = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
      let unit = [
        ["元", "万", "亿"],
        ["", "拾", "佰", "仟"],
      ];
      let head = n < 0 ? "欠" : "";
      n = Math.abs(n);
      let s = "";
      for (let i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, "");
      }
      // s = s || "整";

      n = Math.floor(n);
      for (let i = 0; i < unit[0].length && n > 0; i++) {
        let p = "";
        for (let j = 0; j < unit[1].length && n > 0; j++) {
          p = digit[n % 10] + unit[1][j] + p;
          n = Math.floor(n / 10);
        }
        s = p.replace(/(零.)*零$/, "").replace(/^$/, "零") + unit[0][i] + s;
      }
      return (
        "大写：" + (head + s.replace(/(零.)*零元/, "元").replace(/(零.)+/g, "零"))
        // .replace(/^整$/, "零元整")
      );
    },
    //计算多少年
    formateYear(e) {
      if (e[0]) {
        return `有效期为${CalculationDate(e[0], e[1])}`;
      } else {
        return "";
      }
    },
  },
  data () {
    return {
      RoleType: localStorage.getItem("Role") || "",
      formData:{},
      formRule: {
        CompanyName: [{ required: true, message: "请填写名称", trigger: "blur" }],
        CreditCode: [{ required: true, message: "请填写信用码", trigger: "blur" }],
        Province: [{ 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: "请输入正确的格式,可保留两位小数" },
        ],
        trueUseName: [{ required: true, message: "请输入关键字", trigger: "change" }],
        PayRemark: [{ required: true, message: "请填写付款方式说明", trigger: "blur" }],
      },
      relationContractData: null, //选择的关联合同数据
      ficcServiceData: null, //ficc 底部表格数据
      qyServiceData: null, //权益底部表格数据
      serviceShow: false, //是否显示查看报价单
      serviceCon: {}, //选择的服务项 查看报价单/选择品种

      showEdit:false,//是否显示编辑按钮
    }
  },
  created () {
    this.getDetail()
    this.getContractOperationList()
  },
  methods: {
    // 获取合同详情
    async getDetail(){
      const res=await contractInterface.getContractDetail({
        ContractId:this.$route.query.contractId
      })
      if(res.Ret===200){
        this.formData=res.Data
        this.relationContractData=res.Data.RelationContractDetailList[0]
        this.getServiceList()
        // 本人的合同并且合同状态不为 已审批、待审批、已作废、已签回、已解约 则显示编辑
          let userid=localStorage.getItem('AdminId')
          if(userid==res.Data.SellerId
            &&res.Data.Status!=='待审批'
            &&res.Data.Status!=='已审批'
            &&res.Data.Status!=='已作废'
            &&res.Data.Status!=='已签回'
            &&res.Data.Status!=='已解约'){
            this.showEdit=true
          }else{
            this.showEdit=false
          }
      }
    },

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

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

    //显示查看报价单弹窗
    handleShowService(e) {
      // 小套餐情况处理表格数据
      if (e.Detail) {
        let temarr = e.Detail.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;
        });
        this.serviceCon = { ...e, tableHeadData: temarr[0], tableData: temarr.slice(1) };
      } else {
        this.serviceCon = e;
      }
      this.serviceShow = true;
    },

    //前往预览合同
    handleGoPreview(){
			let {href} = this.$router.resolve({
        path:"/contractdtl",
        query:{contractid:this.$route.query.contractId}
      });
			window.open(href,'_blank');
    },

    //点击编辑 跳转编辑页
    handleGoEdit() {
      this.$router.push({
        path: "/editcontractdc",
        query: {
          contractId: this.$route.query.contractId,
          type: "edit",
        },
      });
    },
  }
}
</script>

<style>
.contractdetail-dc .self-dialog-c .el-dialog__header {
  background-color: #fff;
  padding: 0;
}
.contractdetail-dc .self-dialog-c {
  width: auto;
  /* max-width: 60%; */
}
.contractdetail-dc .el-timeline-item__tail {
  border-left: 2px solid #409eff;
}
.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>
.contractdetail-dc{
    min-height: calc(100vh - 250px);
    position: relative;
    font-size: 16px;
    color: #000;
}
.flex {
  display: flex;
}
.right-wrap {
  margin-left: 20px;
  flex: 1;
  .timeline-wrap {
    margin-top: 20px;
    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;
  }
}
.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>