<template>
  <div class="flex addconstract-container">
    <el-form ref="form" :model="formData" label-position="left" :rules="formRule" label-width="110px" style="width: 80%">
      <section class="section">
        <h2 class="section-title">客户信息</h2>
        <div class="section-container">
          <div class="flex border-top" style="padding-top: 30px">
            <el-form-item label="甲方名称" prop="customeName" style="width: 50%">
              <el-input v-model="formData.CompanyName" placeholder="请输入或者搜索客户名称" style="width: 350px" disabled></el-input>
            </el-form-item>
            <el-form-item label="社会信用码" prop="customeXYM" style="width: 50%">
              <el-input v-model="formData.CreditCode" placeholder="请输入社会信用码" style="width: 350px" disabled></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 :value="formData.Address" disabled placeholder="请输入详细地址" style="width: 350px"></el-input>
            </el-form-item>
          </div>

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

      <section class="section">
        <h2 class="section-title">合同信息</h2>
        <div class="section-container">
          <div class="flex border-top" style="padding-top: 30px">
            <el-form-item label="合同编号" style="width: 50%">
              <span>{{ formData.ContractCode }}</span>
            </el-form-item>
            <el-form-item label="合同归属" style="width: 50%">
              <span>{{ formData.ProductId === 1 ? "ficc" : "权益" }}</span>
            </el-form-item>
          </div>
          <el-form-item label="合同类型" prop="constractType" class="border-top">
            <el-radio-group v-model="formData.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="formData.timeRange">
            <el-form-item label="合同期限" prop="time" style="width: 50%">
              <el-date-picker disabled v-model="formData.timeRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>
            </el-form-item>
            <span style="line-height: 40px">{{ formData.timeRange | formateYear }}</span>
          </div>

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

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

          <el-form-item label="付款方式说明" prop="remark" class="border-top">
            <el-input type="textarea" disabled v-model="formData.PayRemark" placeholder="请输入付款方式说明（请参考以下说明模板填写，请勿填写现金/转账等支付形式）" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="付款方" prop="PayChannel" class="border-top">
            <el-input type="textarea" disabled v-model="formData.PayChannel" placeholder="代付，请填写代付的券商名称或期货公司名称；非代付，请填写无。（请勿填写现金/转账等支付形式）" style="width: 80%"></el-input>
          </el-form-item>
          <!-- <el-form-item label="备注" class="border-top">
            <el-input type="textarea" disabled 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
            :canEdit="false"
            :serviceData="ficcServiceData"
            :hasSercive="formData.Service"
            @handleShowService="handleShowService"
            v-if="formData.ProductId === 1 && ficcServiceData"
          ></FiccServiceTable>

          <!-- 权益 服务内容表格 -->
          <QyServiceTable
            :canEdit="false"
            :serviceData="qyServiceData"
            :hasSercive="formData.Service"
            @handleShowService="handleShowService"
            v-if="formData.ProductId === 2 && qyServiceData"
          ></QyServiceTable>
        </div>

        <p style="margin-top: 30px; margin-bottom: 20px">补充内容（eg额外赠送、路演次数规定）</p>
        <el-radio v-model="radio" label="2" disabled>无</el-radio>
        <el-radio v-model="radio" label="1" disabled>有</el-radio>
        <el-input v-if="radio === '1'" disabled type="textarea" v-model="formData.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="备注" class="border-top">
            <el-input type="textarea" disabled 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="serviceClose" :show-close="false">
      <h2 class="title" style="text-align: center; color: #000">{{ serviceCon.ProductId == '1'? serviceCon.Title : serviceCon.showTitle }}</h2>
      <img class="img" style="width: 100%; display: block; margin: 20px auto" 
      :src="serviceCon.ProductId == '1'? serviceCon.Value : serviceCon.showValue" />
      <!-- <table v-else class="table-wrap">
        <thead>
          <tr style="background: #f0f2f5">
            <th class="table-item" v-for="item in serviceCon.tableHeadData" :key="item.Value">{{ item.Value }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, rindex) in serviceCon.tableData" :key="rindex" :class="rindex === selectRowIndex ? 'row-dark' : null">
            <td class="table-item" v-for="item in row" :key="item">
              <div>{{ item.Value }}</div>
            </td>
          </tr>
        </tbody>
      </table> -->
      <div style="text-align: center; margin-bottom: 30px">
        <el-button type="primary" @click="serviceShow =false">知道了</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import QyServiceTable from "./components/QyServiceTable"; //权益服务内容表格组件
import FiccServiceTable from "./components/FiccServiceTable"; //ficc服务内容表格组件
import { contractInterface } from "@/api/api.js";
import {CalculationDate} from '@/utils/CalculationDate'
export default {
  name: "constractDetail",
  components: {
    QyServiceTable,
    FiccServiceTable,
  },
  // beforeRouteLeave(to, from, next)  {
  //   from.matched[0].name='合同管理'
  //   next()
  // },
  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) {
      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") || "",
      contractId: this.$route.query.contractId,
      operationList: [],//操作记录
      formData: {}, //合同详情数据
      radio: "1", //用于显示底部是否有备注内容
      ficcServiceData: null, //ficc 底部表格数据
      qyServiceData: null, //权益底部表格数据

      serviceShow: false, //是否显示查看报价单
      serviceCon: {}, //选择的服务项 查看报价单/选择品种

      showEdit:false,//是否显示编辑按钮
    };
  },
  created() {

    this.getDetail();
    this.getContractOperationList()

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

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

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

    //显示查看报价单弹窗
    handleShowService(e) {
      console.log(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;
    },

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

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

    // 获取合同详情
    getDetail() {
      contractInterface.getContractDetail({ ContractId: Number(this.contractId) }).then((res) => {
        if (res.Ret === 200) {
          this.formData = { ...res.Data, timeRange: [res.Data.StartDate, res.Data.EndDate] };
          if(res.Data.RelationContractDetailList.length>0){
            let arr=[]
            res.Data.RelationContractDetailList.forEach(item=>{
              arr.push(item.CompanyName)
            })
            this.formData.PayChannel=arr.join('、')
          }
          if (res.Data.Remark) {
            this.radio = "1";
          } else {
            this.radio = "2";
          }
          // 本人的合同并且合同状态不为 已审批、待审批、已作废、已签回、已解约 则显示编辑
          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
          }
          this.getServiceList();
        }
      });
    },
  },
};
</script>

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

<style lang="scss" scoped>
.img{
  image-rendering: -moz-crisp-edges; 
  image-rendering: -o-crisp-edges; 
  image-rendering: -webkit-optimize-contrast; 
  image-rendering: crisp-edges; 
  -ms-interpolation-mode: nearest-neighbor;
}
.addconstract-container {
  min-height: calc(100vh - 250px);
  position: relative;
  font-size: 16px;
  color: #000;
}
.flex {
  display: flex;
}
.section {
  background-color: #fff;
  border: 1px solid #aab4cc;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
  .section-title {
    margin-bottom: 30px;
  }
  .border-top {
    padding-top: 30px;
    border-top: 1px solid #dcdfe6;
  }
}

.right-wrap {
  margin-left: 20px;
  flex: 1;
  .timeline-wrap {
    margin-top: 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;
  }
}

.table-wrap {
  margin: 20px 0;
  position: relative;
  width: 100%;
  text-align: center;
  border-top: 1px solid #ebeef5;
  border-left: 1px solid #ebeef5;
  .row-dark {
    background-color: #deedff;
  }
  .table-item {
    padding: 12px 10px;
    border-right: 1px solid #ebeef5;
    border-bottom: 1px solid #ebeef5;
    min-width: 200px;
    position: relative;
  }
}
</style>
