<template>
  <div class="components-container">
    <el-card>
      <el-form label-width="90px" label-position="right">
        <el-row>
          <el-col :span="6">
            <el-form-item label="合同编号:">
              <el-select v-model="contractNumValue" filterable size="small" placeholder="合同编号" style="width:100%" @change="contractChange">
                <el-option
                  v-for="item in contractNums"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商:">
              <el-input v-model="supplierName" size="small" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="合同名称:">
              <el-input v-model="contractName" size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="是否含税:">
              <el-input v-model="taxRate" size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-tooltip :content="haTtax" placement="top">
              <el-switch
                v-model="haTtax"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="含税"
                inactive-value="未税"
                style="margin: 10px"/>
            </el-tooltip>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="支付日期:">
              <el-input v-model="payDate" size="small" type="textarea" rows="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付方式:">
              <el-input v-model="payMethod" size="small" type="textarea" rows="1"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开票信息:">
              <el-input v-model="invoiceInfo" size="small" type="textarea" rows="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="其他说明:">
              <el-input v-model="otherInfo" size="small" type="textarea" rows="1"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="tableData1" border style="margin-bottom: 10px;max-height: 300px;" height="300px" size="mini" show-summary>
        <el-table-column label="序号" align="center" width="50" type="index"/>
        <el-table-column label="物料计划到货时间" align="center" min-width="130">
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.物料计划到货时间"
              size="mini"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 130px"/>
          </template>
        </el-table-column>
        <el-table-column label="物料名称" align="center" min-width="150">
          <template slot-scope="scope">
            {{ scope.row.物料名称 }}
          </template>
        </el-table-column>
        <el-table-column label="物料规格型号" align="center" min-width="150">
          <template slot-scope="scope">
            {{ scope.row.物料规格 }}
          </template>
        </el-table-column>
        <el-table-column label="订货数量" align="center" min-width="80">
          <template slot-scope="scope">
            {{ scope.row.订货数量 }}
          </template>
        </el-table-column>
        <el-table-column v-show="haTtax==='未税'" label="单价（未税）" align="center" min-width="100">
          <template slot-scope="scope">
            <el-input v-show="haTtax==='未税'" v-model="scope.row.未税单价" size="mini" style="width:70px"/>
            <span v-show="haTtax!=='未税'">—</span>
          </template>
        </el-table-column>
        <el-table-column v-show="haTtax==='含税'" label="单价（含税）" align="center" min-width="100">
          <template slot-scope="scope">
            <el-input v-show="haTtax==='含税'" v-model="scope.row.含税单价" size="mini" style="width:70px"/>
            <span v-show="haTtax!=='含税'">—</span>
          </template>
        </el-table-column>
        <el-table-column label="总额（未税）" align="center" min-width="100" prop="未税总额">
          <template slot-scope="scope">
            {{ haTtax==='未税' ? 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="100" prop="含税总额">
          <template slot-scope="scope">
            {{ haTtax==='含税' ? scope.row.含税总额 = (Number(scope.row.订货数量) * Number(scope.row.含税单价)).toFixed(2) : scope.row.含税总额 = (scope.row.未税总额 * (1+taxRate)).toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>
      <span>合同模板：</span>
      <el-radio-group v-model="demoRadio" size="small" @change="demoChange">
        <el-radio-button label="模板1"/>
        <el-radio-button label="模板2"/>
        <el-radio-button label="模板3"/>
        <el-radio-button label="自定义"/>
      </el-radio-group>
      <el-button type="primary" plain size="small" style="margin-left:10px;" @click="editContract()">调整合同</el-button>
      <el-button type="success" size="small" @click="generateContract()">生成合同</el-button>
      <div style="float: right">
        <span>合同总额：</span>
        <el-input v-model="actualTotal" size="small" style="width: 100px"/>
        <el-button type="primary" size="small" @click="submitTotal()">确定总额</el-button>
      </div>
      <hr>
      <!--html代码-->
      <div v-show="false">{{ content }}</div>
      <!--富文本编辑器-->
      <div v-show="!preview" id="tinymce" style="height:650px;">
        <tinymce ref="tinymce" :height="500" 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 QRCode from 'qrcode'
import { searchInquirySheet, searchSheetContract } from '@/api/PurchasingCenter/CreatePurchaseContract'
import { convertCurrency } from '@/vendor/int2Chinese'
import { mapGetters } from 'vuex'

export default {
  components: { Tinymce },
  data() {
    return {
      haTtax: '未税',
      taxRate: 0.16,
      preview: false, // 预览
      demoRadio: '自定义', // 模板radio
      content: ``, // 合同格式模板
      contentNew: ``, // tinymce的
      contractName: '采购合同', // 合同名称
      contractNum: '', // 合同编号
      contractNums: [], // 合同编号数组
      contractNumValue: '', // 合同流水号
      supplierName: '', // 供应商名称
      supplierAddress: '', // 供应商地址
      untaxTotal: '', // 未税合计
      tax: '', // 税额
      taxTotal: '', // 含税合计
      actualTotal: '', // 实际金额
      actualTotal_zh: '', // 实际金额大写
      payDate: '', // 支付日期
      payMethod: '', // 支付方式
      invoiceInfo: '', // 开票信息
      otherInfo: '', // 其他说明
      tableData1: []
    }
  },
  computed: {
    ...mapGetters([
      'sidebar',
      'avatar',
      'name',
      'id'
    ])
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      searchInquirySheet(0, 0, 0, 0, 1, this.id).then(response => { // 初始化询价单号
        for (let i = 0; i < response.data.length; i++) {
          this.contractNums.push({
            value: response.data[i].询价单流水号,
            label: response.data[i].询价单编号,
            supplierName: response.data[i].供应商名称
          })
        }
      })
    },
    submitTotal() { // 确定合同总额
      this.$refs.tinymce.destroyTinymce()
      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()
    },
    contractChange() { // 选择合同select
      for (let i = 0; i < this.contractNums.length; i++) {
        if (this.contractNums[i].value === this.contractNumValue) {
          this.supplierName = this.contractNums[i].supplierName
          this.contractNum = this.contractNums[i].label
        }
      }
      this.searchContractDetail()
    },
    searchContractDetail() { // 查询合同明细
      this.tableData1 = []
      searchSheetContract(this.contractNumValue).then(response => {
        console.log(response.data)
        for (let i = 0; i < response.data.length; i++) {
          this.tableData1.push({
            物料计划到货时间: response.data[i].物料计划到货时间,
            物料名称: response.data[i].物料名称,
            物料规格: response.data[i].物料规格,
            订货数量: response.data[i].订货数量,
            未税单价: 0,
            未税总额: 0,
            含税单价: 0,
            含税总额: 0
          })
        }
      })
      console.log(this.tableData1)
    },
    demoChange() { // 模板change
      switch (this.demoRadio) {
        case '模板1':
          this.demo1()
          break
        case '模板2':
          this.demo2()
          break
        case '模板3':
          this.demo3()
          break
        case '自定义':
          this.customization()
          break
      }
    },
    demo1() { // 选择合同模板1
      this.content = `
<h1 style="text-align: center;">
    <strong>采购合同</strong>
</h1>
<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%;">&nbsp;</td>
            <td style="width: 25%;" rowspan="2"><img id="qrCode"></td>
        </tr>
        <tr>
            <td style="width: 25%;">
                <h4 style="text-align: center;">合同编号：</h4>
            </td>
            <td id="contractNum" style="width: 25%;">&nbsp;</td>
        </tr>
    </tbody>
</table>
<table style="border-collapse: collapse; width: 100%;" border="1">
    <tbody>
        <tr>
            <td style="width: 25%;">买方：</td>
            <td style="width: 25%;">江苏高精机电装配有限公司</td>
            <td style="width: 25%;">卖方：</td>
            <td id="supplierName" style="width: 25%;">&nbsp;</td>
        </tr>
        <tr>
            <td style="width: 25%;">地址：</td>
            <td style="width: 25%;">盐城市开放大道666号</td>
            <td style="width: 25%;">地址：</td>
            <td id="supplierAddress" style="width: 25%;">&nbsp;</td>
        </tr>
        <tr>
            <td style="width: 25%;">法定代表人：</td>
            <td style="width: 25%;">徐秀兵</td>
            <td style="width: 25%;">法定代表人：</td>
            <td style="width: 25%;">&nbsp;</td>
        </tr>
        <tr>
            <td style="width: 25%;">电话：</td>
            <td style="width: 25%;">&nbsp;</td>
            <td style="width: 25%;">电话：</td>
            <td style="width: 25%;">&nbsp;</td>
        </tr>
        <tr>
            <td style="width: 25%;">传真：</td>
            <td style="width: 25%;">&nbsp;</td>
            <td style="width: 25%;">传真：</td>
            <td style="width: 25%;">&nbsp;</td>
        </tr>
    </tbody>
</table>
<p>根据中华人民共和国合同法及相关法律法规，经买卖双方平等协商，就卖方向买方出售合同项下产品事宜达成一致，签订本合同（明细表及合同通用条款）如下：</p>
<table style="border-collapse: collapse; width: 100%;"
    border="1">
    <tbody>
        <tr>
            <td style="width: 25%;">合同总额（人民币含税）：</td>
            <td class="actualTotal" style="width: 25%;"></td>
            <td style="width: 25%;">大写：</td>
            <td id="actualTotal_zh" style="width: 25%;"></td>
        </tr>
        <tr>
            <td style="width: 25%;">交货日期：</td>
            <td style="width: 25%;" colspan="3">&nbsp;</td>
        </tr>
        <tr>
            <td style="width: 25%;" rowspan="3">交货地点：</td>
            <td style="width: 25%;">地址：</td>
            <td style="width: 25%;" colspan="2">&nbsp;</td>
        </tr>
        <tr>
            <td style="width: 25%;">联系人：</td>
            <td style="width: 25%;" colspan="2">&nbsp;</td>
        </tr>
        <tr>
            <td style="width: 25%;">联系电话：</td>
            <td style="width: 25%;" colspan="2">&nbsp;</td>
        </tr>
        <tr>
            <td style="width: 25%;">开票信息：</td>
            <td style="width: 25%;" colspan="3">
                <p id="invoiceInfo">&nbsp;</p>
            </td>
        </tr>
        <tr>
            <td style="width: 25%;">支付日期：</td>
            <td style="width: 25%;" colspan="3">
                <p id="payDate">&nbsp;</p>
            </td>
        </tr>
        <tr>
            <td style="width: 25%;">支付方式：</td>
            <td style="width: 25%;" colspan="3">
                <p id="payMethod">&nbsp;</p>
            </td>
        </tr>
        <tr>
            <td style="width: 25%;">其他说明：</td>
            <td style="width: 25%;" colspan="3">
                <p id="otherInfo">&nbsp;</p>
            </td>
        </tr>
    </tbody>
</table>
<table style="border-collapse: collapse; width: 100%;" border="1">
    <tbody>
        <tr>
            <td style="width: 50%;">
                <p>买方：</p>
                <p>（盖章）</p>
                <p>授权代表人：_______________</p>
                <p>&nbsp;</p>
                <p>&nbsp;</p>
            </td>
            <td style="width: 50%;">
                <p>卖方：</p>
                <p>（盖章）</p>
                <p>授权代表人：_______________&nbsp;</p>
                <p>&nbsp;</p>
                <p>&nbsp;</p>
            </td>
        </tr>
    </tbody>
</table>
<p style="text-align: right;">日期：______年______月______日</p>
<hr />
<p style="text-align: center;">
    <strong>明细表</strong>
</p>
<table style="border-collapse: collapse; width: 100%;" border="1">
    <tbody id="tbody">
        <tr id="tableHead">
            <td style="width: 5%;">序号</td>
            <td style="width: 10%;">图号</td>
            <td style="width: 10%;">名称</td>
            <td style="width: 10%;">规格型号</td>
            <td style="width: 5%;">数量</td>
            <td style="width: 10%;">单价金额</td>
            <td style="width: 10%;">合计金额</td>
            <td style="width: 12%;">交货时间</td>
            <td style="width: 10%;">备注</td>
        </tr>
    </tbody>
</table>
<br>
<span>未税合计：</span><span id="untaxTotal"></span><br><br>
<span>税额：</span><span id="tax"></span><br><br>
<span>含税总价（税率17%）：</span><span id="taxTotal"></span><br><br>
<span>优惠后含税总价：</span><span class="actualTotal"></span><br><br>
`
    },
    editContract() { // 选择一个询价单，整成合同明细
      this.$refs.tinymce.destroyTinymce()
      const opts = {
        errorCorrectionLevel: 'H',
        type: 'image/jpeg',
        rendererOpts: {
          quality: 0.3
        }
      }
      const str = this.contractNumValue.toString()
      QRCode.toDataURL(str, opts, function(err, url) {
        if (err) throw err
        if (document.getElementById('qrCode')) {
          const img = document.getElementById('qrCode')
          img.src = url
        }
      })
      this.supplierAddress = '无锡市新区新畅南路3号'
      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('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('otherInfo') ? document.getElementById('otherInfo').innerHTML = this.otherInfo : ''
      // 明细表
      // 移出旧数据
      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 tr = []
      for (let i = 0; i < this.tableData1.length; i++) {
        tr[i] = document.createElement('tr')
        tr[i].setAttribute('class', 'tableData')
        tr[i].innerHTML = '<td style="width: 5%;"></td><td style="width: 10%;"></td><td style="width: 10%;"></td><td style="width: 10%;"></td><td style="width: 5%;"></td><td style="width: 10%;"></td><td style="width: 10%;"></td><td style="width: 12%;"></td><td style="width: 10%;"></td>'
        document.getElementById('tableHead') ? document.getElementById('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].含税总额)
        if (document.getElementsByClassName('tableData')[j]) {
          document.getElementsByClassName('tableData')[j].children[0].innerHTML = j + 1
          document.getElementsByClassName('tableData')[j].children[1].innerHTML = `图号` + j
          document.getElementsByClassName('tableData')[j].children[2].innerHTML = this.tableData1[j].物料名称
          document.getElementsByClassName('tableData')[j].children[3].innerHTML = this.tableData1[j].物料规格
          document.getElementsByClassName('tableData')[j].children[4].innerHTML = this.tableData1[j].订货数量
          this.haTtax === '含税' ? document.getElementsByClassName('tableData')[j].children[5].innerHTML = this.tableData1[j].含税单价 : document.getElementsByClassName('tableData')[j].children[5].innerHTML = this.tableData1[j].未税单价
          document.getElementsByClassName('tableData')[j].children[6].innerHTML = Number(document.getElementsByClassName('tableData')[j].children[5].innerHTML) * Number(this.tableData1[j].订货数量)
          document.getElementsByClassName('tableData')[j].children[7].innerHTML = this.tableData1[j].物料计划到货时间.split(' ')[0]
          document.getElementsByClassName('tableData')[j].children[8].innerHTML = `备注` + j
        }
      }
      this.actualTotal = this.actualTotal.toFixed(2)
      this.actualTotal = this.untaxTotal.toFixed(2)
      this.actualTotal = this.taxTotal.toFixed(2)
      this.tax = this.taxTotal - this.untaxTotal
      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') ? document.getElementsByClassName('actualTotal')[0].innerHTML = this.actualTotal : ''
      document.getElementsByClassName('actualTotal') ? document.getElementsByClassName('actualTotal')[1].innerHTML = this.actualTotal : ''
      document.getElementById('actualTotal_zh') ? document.getElementById('actualTotal_zh').innerHTML = this.actualTotal_zh : ''
      this.contentNew = document.getElementsByClassName('editor-content')[0].innerHTML
      this.$refs.tinymce.initTinymce()
    },
    demo2() {
      this.content = `demo2`
    },
    demo3() {
      this.content = `demo3`
    },
    customization() { // 自定义
      this.content = `自定义`
    },
    generateContract() { // 生成采购合同
      this.content = this.contentNew // 更新tinymce中的东西到html中，后续会用到
      if (this.contractNumValue) {
        this.$confirm('此操作将生成采购合同，确认完成编辑？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      } else {
        this.$message.warning('请先选择合同进行编辑')
      }
    }
  }
}
</script>

<style scoped>
  .editor-content{
    margin-top: 20px;
  }
  span{
    margin: 0 0 0 20px;
  }
</style>
