<template>
  <div class="components-container">
    <el-card>
      <el-row>
        <!--<span>供 应 &nbsp;商:</span>-->
        <el-select v-model="supplierValue11" clearable filterable size="small" placeholder="供应商" @focus="fetchData11()" @change="selectHetong()">
          <el-option
            v-for="item in supplier11"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <!--<span>合同编号:</span>-->
        <el-select v-model="contractNumValue" filterable size="small" placeholder="合同编号" @change="contractChange">
          <el-option
            v-for="item in contractNums"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <!--<span>|| 供 应 商:</span>-->
        <el-select v-model="supplierValue" clearable filterable size="small" placeholder="供应商" @focus="fetchData" @change="supplierChange9745">
          <el-option
            v-for="item in supplier"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <!--<span>合同名称:</span>-->
        <el-input v-model="contractName" size="small"/>
        <!--<span>是否含税:</span>-->
        <el-input :disabled="hasTax==='未税'" v-model="taxRate" size="small" style="width: 80px"/>
        <el-tooltip :content="hasTax" placement="top">
          <el-switch
            v-model="hasTax"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="含税"
            inactive-value="未税"/>
        </el-tooltip>
        <el-button v-if="quickChangePrice" size="mini" style="margin: 0px 0 0 10px" @click="quickChangePrice=!quickChangePrice">快速修改价格</el-button>
        <el-button v-else size="mini" style="margin: 10px 0 0 10px" @click="quickChangePrice=!quickChangePrice">还原</el-button>
        <el-button v-show="isShowN" type="text" style="margin: 10px 0 0 10px" @click="isShowN=false">折叠</el-button>
        <el-button v-show="!isShowN" type="text" style="margin: 10px 0 0 10px" @click="isShowN=true">展开其他说明</el-button>
        <el-tooltip v-show="true" :open-delay="300" content="一键删除交货期" placement="right">
          <el-button type="danger" icon="el-icon-date" size="small" @click="deleteAllDate()"/>
        </el-tooltip>
      </el-row>
      <el-row v-show="isShowN" style="margin-top: 10px">
        <!--<span>交货日期:</span>-->
        <el-input v-model="deliveryDate" :disabled="!contractNumValue" size="small" placeholder="交货日期" type="textarea" rows="1" @blur="contractHeaderChange"/>
        <!--<span>开票信息:</span>-->
        <el-input v-model="invoiceInfo" :disabled="!contractNumValue" size="small" placeholder="开票日期" type="textarea" rows="1" @blur="contractHeaderChange"/>
        <!--<span>支付 日期:</span>-->
        <el-input v-model="payDate" :disabled="!contractNumValue" size="small" placeholder="支付日期" type="textarea" rows="1" @blur="contractHeaderChange"/>
        <!--<span>支付方式:</span>-->
        <el-input v-model="payMethod" :disabled="!contractNumValue" size="small" placeholder="支付方式" type="textarea" rows="1" @blur="contractHeaderChange"/>
        <!--<span>其他说明:</span>-->
        <el-input v-model="otherInfo" :disabled="!contractNumValue" size="small" placeholder="其他说明" type="textarea" rows="1" @blur="contractHeaderChange"/>
      </el-row>

      <el-table v-loading="loading" :data="tableData1" border style="margin: 10px 0;max-height: 480px;" height="480px" size="mini" show-summary tooltip-effect="dark">
        <el-table-column label="序号" align="center" width="50" type="index"/>
        <el-table-column label="机床图号" align="center" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.机床图号 }}
          </template>
        </el-table-column>
        <el-table-column label="组号" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.row.组号 }}
          </template>
        </el-table-column>
        <el-table-column label="名称" align="center" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.名称 }}
          </template>
        </el-table-column>
        <el-table-column label="图号或型号" align="center" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.图号 ? scope.row.图号 : '—' }}
          </template>
        </el-table-column>
        <el-table-column label="规格" align="center" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.规格 ? scope.row.规格 : '—' }}
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.row.数量 }}
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" width="80">
          <template slot-scope="scope">
            {{ scope.row.计量单位 }}
          </template>
        </el-table-column>
        <el-table-column v-show="hasTax==='含税'" label="单价（含税）" align="center" width="100">
          <template slot-scope="scope">
            <el-input v-direction="{x: 0, y: scope.$index}" v-if="hasTax==='含税'" v-model="scope.row.含税单价" size="mini" style="width:100%" @keyup.native="scope.row.含税单价 = scope.row.含税单价.replace(/[^\.\d]/g,'')" @change="priceChange(scope.row.含税单价, scope.row.物料流水号, scope.row.询价单流水号, scope.row, scope.row.零件名称, scope.row.零件图号, scope.row.规格)"/>
            <b v-show="hasTax!=='含税'">—</b>
          </template>
        </el-table-column>
        <el-table-column label="总额（含税）" align="center" min-width="100" prop="含税总额">
          <template slot-scope="scope">
            {{ hasTax==='含税' ? scope.row.含税总额 = (Number(scope.row.数量) * Number(scope.row.含税单价)).toFixed(2) : scope.row.含税总额 = (scope.row.未税总额 * (1+taxRate)).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" min-width="80" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-direction="{x: 1, y: scope.$index}" v-if="quickChangePrice" v-model="scope.row.备注" size="mini" style="width:100%" @change="remarkChange(scope.row.备注, scope.row.物料流水号, scope.row.询价单流水号, scope.row, scope.row.零件名称, scope.row.零件图号, scope.row.规格)"/>
            <b v-else>{{ scope.row.备注 || '—' }}</b>
          </template>
        </el-table-column>
        <el-table-column label="交货期" align="center" width="150">
          <template slot-scope="scope">
            <el-date-picker
              v-if="quickChangePrice"
              v-model="scope.row.交货期"
              size="mini"
              type="date"
              style="width: 130px"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"/>
            <b v-else>{{ scope.row.交货期.split(' ')[0] || '—' }}</b>
          </template>
        </el-table-column>
        <el-table-column v-show="hasTax==='未税'" label="单价（未税）" align="center" width="100">
          <template slot-scope="scope">
            <el-input v-direction="{x: 0, y: scope.$index}" v-if="hasTax==='未税'" v-model="scope.row.未税单价" size="mini" style="width:100%" @keyup.native="scope.row.未税单价 = scope.row.未税单价.replace(/[^\.\d]/g,'')" @change="priceChange(scope.row.未税单价, scope.row.物料流水号, scope.row.询价单流水号, scope.row, scope.row.零件名称, scope.row.零件图号, scope.row.规格)"/>
            <b v-show="hasTax!=='未税'">—</b>
          </template>
        </el-table-column>
        <el-table-column label="总额（未税）" align="center" min-width="100" prop="未税总额">
          <template slot-scope="scope">
            {{ hasTax==='未税' ? scope.row.未税总额 = (Number(scope.row.数量) * Number(scope.row.未税单价)).toFixed(2) : scope.row.未税总额 = (scope.row.含税总额 / (1+taxRate)).toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>
      <el-radio-group v-show="false" v-model="demoRadio" size="small" @change="demoChange">
        <el-radio-button label="模板1"/>
        <el-radio-button label="模板2" disabled/>
      </el-radio-group>
      <el-button type="primary" plain size="small" style="margin-left:10px;" @click="editContract()">预览合同</el-button>
      <span>递交审批：</span>
      <el-tooltip :open-delay="1000" effect="dark" content="生成合同并提交审批" placement="top">
        <el-button type="success" size="small" @click="generateContract()">递交</el-button>
      </el-tooltip>
      <hr>
      <!--html代码-->
      <!--<div v-show="false">{{ content }}</div>-->
      <!--富文本编辑器-->
      <!--<div v-show="!preview" id="tinymce" style="height:850px;">-->
      <!--<tinymce ref="tinymce" :height="700" v-model="contentNew" style="width:800px;margin: 0 auto;"/>-->
      <!--</div>-->
      <!--网页预览-->
      <div v-show="!preview" class="editor-content" style="min-height:500px;margin: 0px auto;width:800px;border:1px solid black" v-html="content"/>
    </el-card>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import { initSupplier11, initSupplier, searchInquirySheet, searchSheetContract, doneContract, searchBaseInfo, savePrice, saveContractHeader, searchContractHeader, saveRemark } from '@/api/PurchasingCenter/CreatePurchaseContract'
import { convertCurrency } from '@/vendor/int2Chinese'
import { mapGetters } from 'vuex'
import { sleep, groupBy } from '@/utils/tool'
import $ from 'jquery'

export default {
  components: { Tinymce },
  inject: ['reload'],
  data() {
    return {
      isShowN: false,
      loading: false,
      supplierValue11: '', // 供应商查询条件
      supplier11: [],
      quickChangePrice: true,
      supplier: [],
      year: '',
      month: '',
      day: '',
      trustee: '', // 受托人
      bank1: '',
      account1: '',
      taxCode1: '',
      phone1: '',
      fax1: '',
      postCode1: '',
      bank2: '',
      account2: '',
      taxCode2: '',
      phone2: '',
      fax2: '',
      postCode2: '',
      hasTax: '含税',
      taxRate: 0.13,
      preview: false, // 预览
      demoRadio: '模板1', // 模板radio
      content: ``, // 合同格式模板
      contentNew: ``, // tinymce的
      contractName: '采购合同', // 合同名称
      contractNum: '', // 合同编号
      contractNums: [], // 合同编号数组
      contractNumValue: '', // 合同流水号
      supplierName: '', // 供应商名称
      supplierValue: '', // 供应商流水号
      supplierAddress: '', // 供应商地址
      legalPerson: '', // 法人
      untaxTotal: '', // 未税合计
      tax: '', // 税额
      taxTotal: '', // 含税合计
      actualTotal: '', // 实际金额
      actualTotal_zh: '', // 实际金额大写
      payDate: '', // 支付日期
      payMethod: '', // 支付方式
      deliveryDate: '', // 交货日期
      invoiceInfo: '', // 开票信息
      otherInfo: '', // 其他说明
      tableData1: [],
      单价是否含税: '',
      组件零件流水号组: [],
      组件零件基本件流水号组: [],
      数量组: [],
      单价组: [],
      交货期组: [],
      备注组: [],
      companyAddress: '',
      sendAddress: ''
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'id'
    ])
  },
  created() {
    this.fetchData11()
    this.fetchData()
    this.initDirection()
    this.demo1()
  },
  methods: {
    fetchData11() {
      initSupplier11(this.id).then(res => {
        this.supplier11 = []
        for (let i = 0; i < res.data.length; i++) {
          this.supplier11.push({
            value: res.data[i].供应商流水号,
            label: res.data[i].供应商名称
          })
        }
      })
    },
    selectHetong() {
      this.contractNumValue = ''
      this.tableData1 = []
      if (this.supplierValue11) { this.asdasd = 1 } else { this.asdasd = 0 }
      searchInquirySheet(0, 0, 1, this.id, this.asdasd, this.supplierValue11).then(response => { // 初始化询价单号
        this.contractNums = []
        for (let i = 0; i < response.data.length; i++) {
          this.contractNums.push({
            value: response.data[i].询价单流水号,
            label: response.data[i].询价单编号,
            supplierName: response.data[i].供应商名称,
            supplierValue: response.data[i].供应商流水号,
            supplierAddress: response.data[i].地址,
            legalPerson: response.data[i].企业性质, // 法人
            trustee: response.data[i].注册资本 || '', // 受托人
            bank1: response.data[i].开户行 || '', // 开户行
            account1: response.data[i].帐号 || '', // 帐号
            taxCode1: response.data[i].税号 || '', // 税号
            phone1: response.data[i].电话号码 || '', // 电话
            fax1: response.data[i].传真 || '', // 传真
            postCode1: response.data[i].货期 || '' // 邮编
          })
        }
      })
    },
    initDirection() {
      const direction = this.$getDirection()
      direction.on('keyup', function(e, val) {
        if (e.keyCode === 39) {
          direction.next()
        }
        if (e.keyCode === 37) {
          direction.previous()
        }
        if (e.keyCode === 38) {
          direction.previousLine()
        }
        if (e.keyCode === 40) {
          direction.nextLine()
        }
      })
    },
    // 合同头实时保存
    contractHeaderChange() {
      if (this.contractNumValue) {
        saveContractHeader(this.deliveryDate || '', this.invoiceInfo || '', this.payDate || '', this.payMethod || '', this.otherInfo || '', this.contractNumValue).then(res => {
          if (res.data[0].result === '1') {
            console.log('合同头实时保存成功')
          } else {
            console.log('合同头实时保存失败')
          }
        })
      }
    },
    // 备注实时保存
    remarkChange(remark, num1, num2, row, num3, num4, num5) {
      this.tableData1.map(v => {
        v.物料流水号 = v.物料流水号 || ''
        v.零件名称 = v.零件名称 || ''
        v.零件图号 = v.零件图号 || ''
        v.规格 = v.规格 || ''
        row.物料流水号 = row.物料流水号 || ''
        row.零件名称 = row.零件名称 || ''
        row.零件图号 = row.零件图号 || ''
        row.规格 = row.规格 || ''
        if (Number(v.物料流水号) === Number(row.物料流水号) && Number(v.询价单流水号) === Number(row.询价单流水号) && v.零件名称 === row.零件名称 && v.零件图号 === row.零件图号 && v.规格 === row.规格) {
          v.备注 = row.备注
        }
      })
      const group = this.tableData1
      this.tableData1 = []
      this.tableData1 = group
      remark = remark || ''
      num1 = num1 || ''
      num3 = num3 || ''
      num4 = num4 || ''
      num5 = num5 || ''
      saveRemark(remark, num1, num2, num3, num4, num5).then(res => {
        if (res.data[0].result === '1') {
          console.log('备注实时保存成功')
        } else {
          console.log('备注实时保存失败')
        }
      })
    },
    // 价格实时保存
    priceChange(price, num1, num2, row, num3, num4, num5) {
      this.tableData1.map(v => {
        v.物料流水号 = v.物料流水号 || ''
        v.零件名称 = v.零件名称 || ''
        v.零件图号 = v.零件图号 || ''
        v.规格 = v.规格 || ''
        row.物料流水号 = row.物料流水号 || ''
        row.零件名称 = row.零件名称 || ''
        row.零件图号 = row.零件图号 || ''
        row.规格 = row.规格 || ''
        if (Number(v.物料流水号) === Number(row.物料流水号) && Number(v.询价单流水号) === Number(row.询价单流水号) && v.零件名称 === row.零件名称 && v.零件图号 === row.零件图号 && v.规格 === row.规格) {
          v.含税单价 = row.含税单价
          v.未税单价 = row.未税单价
        }
      })
      const group = this.tableData1
      this.tableData1 = []
      this.tableData1 = group
      price = price || 0
      num1 = num1 || ''
      num3 = num3 || ''
      num4 = num4 || ''
      num5 = num5 || ''
      savePrice(price, num1, num2, num3, num4, num5).then(res => {
        if (res.data[0].result === '1') {
          console.log('单价实时保存成功')
        } else {
          console.log('单价实时保存失败')
        }
      })
    },
    deleteAllDate() {
      this.tableData1.map(v => {
        v.交货期 = ''
      })
    },
    fetchData() {
      initSupplier(this.id).then(res => {
        // this.id
        this.supplier = []
        for (let i = 0; i < res.data.length; i++) {
          this.supplier.push({
            value: res.data[i].供应商流水号,
            label: res.data[i].供应商名称
          })
        }
      })
      searchBaseInfo(this.id).then(res => {
        this.companyAddress = res.data[0] ? res.data[0].公司地址 : ''
        this.sendAddress = res.data[0] ? res.data[0].送货地址 : ''
        this.fax2 = res.data[0] ? res.data[0].传真 : ''
        this.postCode2 = '224053'
        this.phone2 = res.data[0] ? res.data[0].手机 + '/' + res.data[0].公司电话 : ''
        this.taxCode2 = res.data[0] ? res.data[0].税号 : ''
        this.account2 = res.data[0] ? res.data[0].帐号 : ''
        this.bank2 = res.data[0] ? res.data[0].开户行 : ''
      })
      searchInquirySheet(0, 0, 1, this.id, 0, 0).then(response => { // 初始化询价单号
        this.contractNums = []
        for (let i = 0; i < response.data.length; i++) {
          this.contractNums.push({
            value: response.data[i].询价单流水号,
            label: response.data[i].询价单编号,
            supplierName: response.data[i].供应商名称,
            supplierValue: response.data[i].供应商流水号,
            supplierAddress: response.data[i].地址,
            legalPerson: response.data[i].企业性质, // 法人
            trustee: response.data[i].注册资本 || '', // 受托人
            bank1: response.data[i].开户行 || '', // 开户行
            account1: response.data[i].帐号 || '', // 帐号
            taxCode1: response.data[i].税号 || '', // 税号
            phone1: response.data[i].电话号码 || '', // 电话
            fax1: response.data[i].传真 || '', // 传真
            postCode1: response.data[i].货期 || '' // 邮编
          })
        }
      })
    },
    submitTotal() { // 确定合同总额
      // this.$refs.tinymce.destroyTinymce()
      // this.$refs.tinymce.initTinymce()
      document.getElementsByClassName('actualTotal')[0].innerHTML = this.actualTotal
      document.getElementsByClassName('actualTotal')[1].innerHTML = this.actualTotal
      document.getElementById('actualTotal_zh').innerHTML = convertCurrency(this.actualTotal)
      this.contentNew = document.getElementsByClassName('editor-content')[0].innerHTML
      setTimeout(() => {
        this.$refs.tinymce.setContent(this.contentNew)
      }, 1000)
      // this.$refs.tinymce.initTinymce()
    },
    supplierChange() {
      let check
      this.supplierValue ? check = 1 : check = 0
      searchInquirySheet(0, 0, 1, this.id, check, this.supplierValue).then(response => { // 初始化询价单号
        this.contractNums = []
        this.contractNumValue = ''
        for (let i = 0; i < response.data.length; i++) {
          this.contractNums.push({
            value: response.data[i].询价单流水号,
            label: response.data[i].询价单编号,
            supplierName: response.data[i].供应商名称,
            supplierValue: response.data[i].供应商流水号,
            supplierAddress: response.data[i].地址,
            legalPerson: response.data[i].企业性质, // 法人
            trustee: response.data[i].注册资本 || '', // 受托人
            bank1: response.data[i].开户行 || '', // 开户行
            account1: response.data[i].帐号 || '', // 帐号
            taxCode1: response.data[i].税号 || '', // 税号
            phone1: response.data[i].电话号码 || '', // 电话
            fax1: response.data[i].传真 || '', // 传真
            postCode1: response.data[i].货期 || '' // 邮编
          })
        }
      })
    },
    supplierChange9745() {
      for (let i = 0; i < this.supplier.length; i++) {
        if (this.supplier[i].value === this.supplierValue) {
          this.supplierName = this.supplier[i].label
        }
      }
    },
    contractChange() { // 选择合同select
      this.loading = true
      searchContractHeader(this.contractNumValue).then(response => {
        this.deliveryDate = response.data[0].交货日期
        this.invoiceInfo = response.data[0].开票信息
        this.payDate = response.data[0].支付日期
        this.payMethod = response.data[0].支付方式
        this.otherInfo = response.data[0].其他说明
      })
      for (let i = 0; i < this.contractNums.length; i++) {
        if (this.contractNums[i].value === this.contractNumValue) {
          this.supplierName = this.contractNums[i].supplierName
          this.supplierValue = this.contractNums[i].supplierValue
          this.supplierAddress = this.contractNums[i].supplierAddress
          this.legalPerson = this.contractNums[i].legalPerson
          this.contractNum = this.contractNums[i].label
          this.trustee = this.contractNums[i].trustee
          this.bank1 = this.contractNums[i].bank1
          this.account1 = this.contractNums[i].account1
          this.taxCode1 = this.contractNums[i].taxCode1
          this.phone1 = this.contractNums[i].phone1
          this.fax1 = this.contractNums[i].fax1
          this.postCode1 = this.contractNums[i].postCode1
        }
      }
      this.searchContractDetail()
    },
    searchContractDetail() { // 查询合同明细
      this.tableData1 = []
      searchSheetContract(this.contractNumValue).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.tableData1.push({
            询价单流水号: response.data[i].询价单流水号,
            物料流水号: response.data[i].物料流水号,
            零件名称: response.data[i].零件名称,
            零件图号: response.data[i].零件图号,
            询价单明细流水号: response.data[i].询价单明细流水号,
            机床图号: response.data[i].机床图号 || response.data[i].基本件机床图号,
            组号: response.data[i].组号 || response.data[i].基本件组号,
            组件零件流水号: response.data[i].组件零件流水号,
            组件零件基本件流水号: response.data[i].组件零件基本件流水号,
            交货期: response.data[i].组件零件流水号 ? response.data[i].标准件和外购件交货期 : response.data[i].基本件交货期,
            图号: response.data[i].组件零件流水号 ? response.data[i].物料型号 : response.data[i].零件图号,
            名称: response.data[i].组件零件流水号 ? response.data[i].物料名称 : response.data[i].零件名称,
            规格: response.data[i].组件零件流水号 ? response.data[i].物料规格 : response.data[i].规格,
            数量: response.data[i].数量,
            计量单位: response.data[i].计量单位,
            未税单价: response.data[i].单价,
            未税总额: 0,
            含税单价: response.data[i].单价,
            含税总额: 0,
            备注: response.data[i].备注
          })
        }
        this.loading = false
      })
    },
    demoChange() { // 模板change
      switch (this.demoRadio) {
        case '模板1':
          this.demo1()
          break
        case '模板2':
          this.demo2()
          break
        // case '自定义':
        //   this.customization()
        //   break
      }
    },
    demo1() { // 选择合同模板1
      this.content = `
<h2 style="text-align: center;">
  <strong>采购合同</strong>
</h2>
<table style="border-collapse: collapse; width: 100%;" border="1">
  <tbody>
      <tr>
          <td style="width: 25%; text-align: center;" rowspan="2">
              <h1>
                  <strong>GAOJING</strong>
              </h1>
          </td>
          <td style="width: 25%;">
              <h4 style="text-align: center;">合同名称：</h4>
          </td>
          <td id="contractName" style="width: 25%;text-align: center;"></td>
          <td style="width: 25%;text-align: center;" rowspan="2"></td>
      </tr>
      <tr>
          <td style="width: 25%;">
              <h4 style="text-align: center;">合同编号：</h4>
          </td>
          <td id="contractNum" style="width: 25%;text-align: center;"></td>
      </tr>
  </tbody>
</table>
<table style="border-collapse: collapse; width: 100%;" border="1">
  <tbody>
      <tr>
          <td style="width: 15%;">买方：</td>
          <td style="width: 35%;">江苏高精机电装配有限公司</td>
          <td style="width: 15%;">卖方：</td>
          <td id="supplierName" style="width: 35%;"></td>
      </tr>
      <tr>
          <td style="width: 15%;">地址：</td>
          <td style="width: 35%;">${this.companyAddress}</td>
          <td style="width: 15%;">地址：</td>
          <td id="supplierAddress" style="width: 35%;"></td>
      </tr>
      <tr>
          <td style="width: 15%;">法定代表人：</td>
          <td style="width: 35%;">徐秀兵</td>
          <td style="width: 15%;">法定代表人：</td>
          <td id="legalPerson" style="width: 35%;"></td>
      </tr>
  </tbody>
</table>
<p>根据中华人民共和国合同法及相关法律法规，经买卖双方平等协商，就卖方向买方出售合同项下产品事宜达成一致，签订本合同（明细表及合同通用条款）如下：</p>
<table style="border-collapse: collapse; width: 100%;" border="1">
  <tbody>
      <tr>
          <td style="width: 20%;">合同总额（RMB）：</td>
          <td class="actualTotal" style="width: 20%;"></td>
          <td style="width: 20%;">大写：</td>
          <td id="actualTotal_zh" style="width: 40%;"></td>
      </tr>
      <tr>
          <td style="width: 20%;" rowspan="3">交货地点：</td>
          <td style="width: 20%;">地址：</td>
          <td style="width: 30%;" colspan="2">${this.sendAddress}</td>
      </tr>
      <tr>
          <td style="width: 20%;">联系人：</td>
          <td style="width: 30%;" colspan="2">${this.name}</td>
      </tr>
      <tr>
          <td style="width: 20%;">联系电话：</td>
          <td style="width: 30%;" colspan="2">${this.phone2}</td>
      </tr>
      <tr>
          <td style="width: 20%;">交货日期：</td>
          <td id="deliveryDate" style="width: 30%;" colspan="3"></td>
      </tr>
      <tr>
          <td style="width: 20%;">开票信息：</td>
          <td id="invoiceInfo" style="width: 30%;" colspan="3"></td>
      </tr>
      <tr>
          <td style="width: 20%;">支付日期：</td>
          <td id="payDate" style="width: 30%;" colspan="3"></td>
      </tr>
      <tr>
          <td style="width: 20%;">支付方式：</td>
          <td id="payMethod" style="width: 30%;" colspan="3"></td>
      </tr>
      <tr>
          <td style="width: 20%;">其他说明：</td>
          <td id="otherInfo" style="width: 30%;" colspan="3"></td>
      </tr>
  </tbody>
</table>
<table style="border-collapse: collapse; width: 100%;" border="1">
  <tbody>
      <tr>
          <td style="width: 50%;">
              <span>卖方：${this.supplierName}（盖章）</span><br>
              <span>受托人：${this.trustee}</span><br>
              <span>开户行：${this.bank1}</span><br>
              <span>账号：${this.account1}</span><br>
              <span>税号：${this.taxCode1}</span><br>
              <span>电话：${this.phone1}</span><br>
              <span>传真：${this.fax1}</span><br>
              <span>邮编：${this.postCode1}</span>
          </td>
          <td style="width: 50%;">
              <span>买方：江苏高精机电装配有限公司（盖章）</span><br>
              <span>受托人：${this.name}</span><br>
              <span>开户行：${this.bank2}</span><br>
              <span>账号：${this.account2}</span><br>
              <span>税号：${this.taxCode2}</span><br>
              <span>电话：${this.phone2}</span><br>
              <span>传真：${this.fax2}</span><br>
              <span>邮编：${this.postCode2}</span>
          </td>
      </tr>
  </tbody>
</table>
<p style="text-align: right;">日期：_${this.year}_年_${this.month}_月_${this.day}_日</p>
<hr />
<p style="text-align: center;">
  <strong>明细表</strong>
  (<strong id="hasTax"></strong>)
</p>
<table style="border-collapse: collapse; width: 100%;" border="1">
  <tbody id="tbody">
      <tr id="tableHead">
          <td>序号</td>
          <td>机床号-组号</td>
          <td>名称</td>
          <td>图号或型号</td>
          <td>规格</td>
          <td>数量</td>
          <td>单位</td>
          <td>单价</td>
          <td>合计</td>
          <td>交货时间</td>
          <td>备注</td>
      </tr>
  </tbody>
</table>
<span>未税合计：</span><span id="untaxTotal"></span><span>元</span><br>
<span>税额：</span><span id="tax"></span><br>
<span>含税总价（税率<span id="taxRate"></span>）：</span><span id="taxTotal"></span><span>元</span><br>
<span>优惠后含税总价：</span><span class="actualTotal"></span><span>元</span>
`
    },
    async editContract() { // 选择一个询价单，整成合同明细
      const date = new Date()
      this.year = date.getFullYear()
      this.month = date.getMonth() + 1
      this.day = date.getDate()
      this.demoChange()
      await sleep(0)
      if (this.contractNumValue) {
        if (this.demoRadio) {
          // this.$refs.tinymce.destroyTinymce()
          document.getElementById('contractName') ? document.getElementById('contractName').innerHTML = this.contractName : ''
          document.getElementById('contractNum') ? document.getElementById('contractNum').innerHTML = this.contractNum : ''
          document.getElementById('supplierName') ? document.getElementById('supplierName').innerHTML = this.supplierName : ''
          document.getElementById('supplierAddress') ? document.getElementById('supplierAddress').innerHTML = this.supplierAddress : ''
          document.getElementById('legalPerson') ? document.getElementById('legalPerson').innerHTML = this.legalPerson : ''
          document.getElementById('payDate') ? document.getElementById('payDate').innerHTML = this.payDate : ''
          document.getElementById('payMethod') ? document.getElementById('payMethod').innerHTML = this.payMethod : ''
          document.getElementById('invoiceInfo') ? document.getElementById('invoiceInfo').innerHTML = this.invoiceInfo : ''
          document.getElementById('deliveryDate') ? document.getElementById('deliveryDate').innerHTML = this.deliveryDate : ''
          document.getElementById('otherInfo') ? document.getElementById('otherInfo').innerHTML = this.otherInfo : ''
          document.getElementById('hasTax') ? document.getElementById('hasTax').innerHTML = this.hasTax : ''
          document.getElementById('taxRate') ? document.getElementById('taxRate').innerHTML = this.taxRate * 100 + '%' : ''
          // 明细表
          // 移出旧数据
          const children = document.getElementsByClassName('tableData')
          const parent = document.getElementById('tbody')
          if (children.length !== 0) {
            for (let i = children.length - 1; i >= 0; i--) {
              parent.removeChild(children[i])
            }
          }
          const merge = []
          this.tableData1.map(v => {
            if ((this.hasTax === '含税' && v.含税单价.trim() !== '') || (this.hasTax === '未税' && v.未税单价.trim() !== '')) { // 筛掉未询到价格的物料
              merge.push({
                机床图号: v.机床图号,
                组号: v.组号,
                图号: v.图号,
                名称: v.名称,
                规格: v.规格,
                数量: Number(v.数量),
                计量单位: v.计量单位,
                单价: this.hasTax === '含税' ? v.含税单价 : v.未税单价,
                合计: (Number(v.数量) * (this.hasTax === '含税' ? Number(v.含税单价) : Number(v.未税单价))).toFixed(2),
                交货期: v.交货期 ? v.交货期.split(' ')[0] : '',
                备注: v.备注
              })
            }
          })
          let mergeData = []
          mergeData = groupBy(merge, ['图号', '名称', '规格', '计量单位', '单价', '交货期', '备注'])
          // 放入新数据
          const tr = []
          for (let i = 0; i < mergeData.length; i++) {
            tr[i] = document.createElement('tr')
            tr[i].setAttribute('class', 'tableData')
            tr[i].innerHTML = '<td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>'
            const tableHead = $('#tableHead')
            tableHead ? tableHead.after(tr[i]) : ''
          }
          this.actualTotal = 0
          this.untaxTotal = 0
          this.taxTotal = 0
          for (let j = 0; j < this.tableData1.length; j++) {
            this.actualTotal += Number(this.tableData1[j].含税总额)
            this.untaxTotal += Number(this.tableData1[j].未税总额)
            this.taxTotal += Number(this.tableData1[j].含税总额)
          }
          for (let j = 0; j < mergeData.length; j++) {
            if (document.getElementsByClassName('tableData')[j]) {
              document.getElementsByClassName('tableData')[j].children[0].innerHTML = j + 1
              document.getElementsByClassName('tableData')[j].children[1].innerHTML = mergeData[j].机床图号_组号
              document.getElementsByClassName('tableData')[j].children[2].innerHTML = mergeData[j].名称
              document.getElementsByClassName('tableData')[j].children[3].innerHTML = mergeData[j].图号
              document.getElementsByClassName('tableData')[j].children[4].innerHTML = mergeData[j].规格
              document.getElementsByClassName('tableData')[j].children[5].innerHTML = mergeData[j].数量
              document.getElementsByClassName('tableData')[j].children[6].innerHTML = mergeData[j].计量单位
              document.getElementsByClassName('tableData')[j].children[7].innerHTML = mergeData[j].单价
              document.getElementsByClassName('tableData')[j].children[8].innerHTML = (Number(mergeData[j].数量) * Number(mergeData[j].单价)).toFixed(2)
              document.getElementsByClassName('tableData')[j].children[9].innerHTML = mergeData[j].交货期
              document.getElementsByClassName('tableData')[j].children[10].innerHTML = mergeData[j].备注
            }
          }
          this.actualTotal = this.actualTotal.toFixed(2)
          this.untaxTotal = this.untaxTotal.toFixed(2)
          this.taxTotal = this.taxTotal.toFixed(2)
          this.tax = (this.taxTotal - this.untaxTotal).toFixed(2)
          document.getElementById('untaxTotal') ? document.getElementById('untaxTotal').innerHTML = this.untaxTotal : ''
          document.getElementById('tax') ? document.getElementById('tax').innerHTML = this.tax : ''
          document.getElementById('taxTotal') ? document.getElementById('taxTotal').innerHTML = this.taxTotal : ''
          document.getElementsByClassName('actualTotal')[0] ? document.getElementsByClassName('actualTotal')[0].innerHTML = this.actualTotal : ''
          document.getElementsByClassName('actualTotal')[1] ? document.getElementsByClassName('actualTotal')[1].innerHTML = this.actualTotal : ''
          document.getElementById('actualTotal_zh') ? document.getElementById('actualTotal_zh').innerHTML = this.actualTotal_zh : ''
          document.getElementsByClassName('actualTotal')[0].innerHTML = this.actualTotal
          document.getElementsByClassName('actualTotal')[1].innerHTML = this.actualTotal
          document.getElementById('actualTotal_zh').innerHTML = convertCurrency(this.actualTotal)
          this.contentNew = document.getElementsByClassName('editor-content')[0].innerHTML
          // this.$refs.tinymce.initTinymce()
          setTimeout(() => {
            this.$refs.tinymce.setContent(this.contentNew)
          }, 1000)
        } else {
          this.$message.warning('请先选择合同模板，再预览')
        }
      } else {
        this.$message.warning('请先选择合同，再预览')
      }
    },
    demo2() {
      this.content = `demo2`
    },
    // customization() { // 自定义
    //   this.content = `自定义`
    // },
    generateContract() { // 生成采购合同
      this.content = this.contentNew.replace(/&nbsp;/g, '')
      this.content = this.content.replace(/\n/g, '')
      this.content = this.content.replace(/==/g, '= =') // 更新tinymce中的东西到html中，后续会用到
      this.组件零件流水号组 = []
      this.组件零件基本件流水号组 = []
      this.数量组 = []
      this.单价组 = []
      this.交货期组 = []
      this.hasTax === '含税' ? this.单价是否含税 = 1 : this.单价是否含税 = 0
      const inquiryDetailNum_old = [] // 需要转移到新询价单的物料的询价单明细流水号
      this.tableData1.map(v => {
        if ((this.hasTax === '含税' && Number(v.含税单价)) || (this.hasTax === '未税' && Number(v.未税单价))) { // 筛掉未询到价格的物料
          this.组件零件流水号组.push(v.组件零件流水号)
          this.组件零件基本件流水号组.push(v.组件零件基本件流水号)
          this.数量组.push(v.数量)
          this.hasTax === '含税' ? this.单价组.push(v.含税单价) : this.单价组.push(v.未税单价)
          this.交货期组.push(v.交货期)
          this.备注组.push(v.备注)
        } else { // 获取未询到价格的物料的询价单明细流水号们
          inquiryDetailNum_old.push(v.询价单明细流水号)
        }
      })
      if (this.contractNumValue) {
        if (this.demoRadio) {
          this.$confirm('此采购合同将递交审批，递交后该合同不可删除，确认完成编辑？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            doneContract(this.contractNum, this.contractName, this.deliveryDate, this.payDate, this.payMethod, this.invoiceInfo, this.otherInfo, this.actualTotal, this.id, this.supplierValue, this.单价是否含税, this.组件零件流水号组, this.组件零件基本件流水号组, this.数量组, this.单价组, this.交货期组, this.content, this.taxRate * 100, inquiryDetailNum_old, this.备注组).then(response => {
              if (response.data[0].result === '1') {
                this.$message.success('合同生成成功')
                this.reload()
              } else {
                this.$message.error('生成合同失败')
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            })
          })
        } else {
          this.$message.warning('请先选择模板进行预览')
        }
      } else {
        this.$message.warning('请先选择合同进行编辑')
      }
    }
  }
}
</script>

<style scoped>
  .editor-content{
    margin-top: 20px;
  }
  span{
    margin: 0 0 0 5px;
  }
  .el-form-item{
    margin: 0;
  }
  .el-select{
    width:150px;
    margin-right: 10px;
  }
  .el-input{
    width:150px;
    margin-right: 10px;
  }
  .el-textarea{
    width:150px;
    margin-right: 10px;
  }
</style>
