<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="hasTax" placement="top">
              <el-switch
                v-model="hasTax"
                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="deliveryDate" size="small" type="textarea" rows="1"/>
            </el-form-item>
          </el-col>
          <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-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="24">
            <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: 10px 0;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" width="150">
          <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:100%"/>
          </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="100">
          <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" width="80">
          <template slot-scope="scope">
            {{ scope.row.数量 }}
          </template>
        </el-table-column>
        <el-table-column v-show="hasTax==='未税'" label="单价（未税）" align="center" width="120">
          <template slot-scope="scope">
            <el-input v-show="hasTax==='未税'" v-model="scope.row.未税单价" size="mini" style="width:100%"/>
            <span v-show="hasTax!=='未税'">—</span>
          </template>
        </el-table-column>
        <el-table-column v-show="hasTax==='含税'" label="单价（含税）" align="center" width="120">
          <template slot-scope="scope">
            <el-input v-show="hasTax==='含税'" v-model="scope.row.含税单价" size="mini" style="width:100%"/>
            <span v-show="hasTax!=='含税'">—</span>
          </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="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>
      <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>
      <span>合同总额：</span>
      <el-input v-model="actualTotal" size="small" style="width: 100px"/>
      <el-button type="primary" size="small" @click="submitTotal()">确定总额</el-button>
      <div style="float: right">
        <el-button type="success" size="small" @click="generateContract()">递交审批</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 { searchInquirySheet, searchSheetContract, doneContract } from '@/api/PurchasingCenter/CreatePurchaseContract'
import { convertCurrency } from '@/vendor/int2Chinese'
import { mapGetters } from 'vuex'

export default {
  components: { Tinymce },
  inject: ['reload'],
  data() {
    return {
      hasTax: '未税',
      taxRate: 0.16,
      preview: false, // 预览
      demoRadio: '自定义', // 模板radio
      content: ``, // 合同格式模板
      contentNew: ``, // tinymce的
      contractName: '采购合同', // 合同名称
      contractNum: '', // 合同编号
      contractNums: [], // 合同编号数组
      contractNumValue: '', // 合同流水号
      supplierName: '', // 供应商名称
      supplierValue: '', // 供应商流水号
      supplierAddress: '', // 供应商地址
      supplierPhone: '', // 供应商电话
      supplierFax: '', // 供应商传真
      untaxTotal: '', // 未税合计
      tax: '', // 税额
      taxTotal: '', // 含税合计
      actualTotal: '', // 实际金额
      actualTotal_zh: '', // 实际金额大写
      payDate: '', // 支付日期
      payMethod: '', // 支付方式
      deliveryDate: '', // 交货日期
      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].供应商名称,
            supplierValue: response.data[i].供应商流水号,
            supplierAddress: response.data[i].地址,
            supplierPhone: response.data[i].电话号码,
            supplierFax: 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.supplierValue = this.contractNums[i].supplierValue
          this.supplierAddress = this.contractNums[i].supplierAddress
          this.supplierPhone = this.contractNums[i].supplierPhone
          this.supplierFax = this.contractNums[i].supplierFax
          this.contractNum = this.contractNums[i].label
        }
      }
      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].数量,
            未税单价: 0,
            未税总额: 0,
            含税单价: 0,
            含税总额: 0,
            备注: response.data[i].备注
          })
        }
      })
    },
    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 = `
<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: 20%;">买方：</td>
            <td style="width: 30%;">江苏高精机电装配有限公司</td>
            <td style="width: 20%;">卖方：</td>
            <td id="supplierName" style="width: 30%;"></td>
        </tr>
        <tr>
            <td style="width: 20%;">地址：</td>
            <td style="width: 30%;">盐城市开放大道666号</td>
            <td style="width: 20%;">地址：</td>
            <td id="supplierAddress" style="width: 30%;"></td>
        </tr>
        <tr>
            <td style="width: 20%;">法定代表人：</td>
            <td style="width: 30%;">徐秀兵</td>
            <td style="width: 20%;">法定代表人：</td>
            <td style="width: 30%;"></td>
        </tr>
        <tr>
            <td style="width: 20%;">电话：</td>
            <td style="width: 30%;"></td>
            <td style="width: 20%;">电话：</td>
            <td id="supplierPhone" style="width: 30%;"></td>
        </tr>
        <tr>
            <td style="width: 20%;">传真：</td>
            <td style="width: 30%;"></td>
            <td style="width: 20%;">传真：</td>
            <td id="supplierFax" style="width: 30%;"></td>
        </tr>
    </tbody>
</table>
<p>根据中华人民共和国合同法及相关法律法规，经买卖双方平等协商，就卖方向买方出售合同项下产品事宜达成一致，签订本合同（明细表及合同通用条款）如下：</p>
<table style="border-collapse: collapse; width: 100%;"
    border="1">
    <tbody>
        <tr>
            <td style="width: 25%;">合同总额（RMB）：</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 id="deliveryDate" style="width: 25%;" colspan="3"></td>
        </tr>
        <tr>
            <td style="width: 25%;" rowspan="3">交货地点：</td>
            <td style="width: 25%;">地址：</td>
            <td style="width: 25%;" colspan="2"></td>
        </tr>
        <tr>
            <td style="width: 25%;">联系人：</td>
            <td style="width: 25%;" colspan="2"></td>
        </tr>
        <tr>
            <td style="width: 25%;">联系电话：</td>
            <td style="width: 25%;" colspan="2"></td>
        </tr>
        <tr>
            <td style="width: 25%;">开票信息：</td>
            <td id="invoiceInfo" style="width: 25%;" colspan="3"></td>
        </tr>
        <tr>
            <td style="width: 25%;">支付日期：</td>
            <td id="payDate" style="width: 25%;" colspan="3"></td>
        </tr>
        <tr>
            <td style="width: 25%;">支付方式：</td>
            <td id="payMethod" style="width: 25%;" colspan="3"></td>
        </tr>
        <tr>
            <td style="width: 25%;">其他说明：</td>
            <td id="otherInfo" style="width: 25%;" colspan="3"></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>
            </td>
            <td style="width: 50%;">
                <p>卖方：</p>
                <p>（盖章）</p>
                <p>授权代表人：_______________</p>
            </td>
        </tr>
    </tbody>
</table>
<p style="text-align: right;">日期：______年______月______日</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>
<br>
<span>未税合计：</span><span id="untaxTotal"></span><span>元</span><br><br>
<span>税额：</span><span id="tax"></span><br><br>
<span>含税总价（税率<span id="taxRate"></span>）：</span><span id="taxTotal"></span><span>元</span><br><br>
<span>优惠后含税总价：</span><span class="actualTotal"></span><span>元</span><br><br>
`
    },
    editContract() { // 选择一个询价单，整成合同明细
      if (this.contractNumValue) {
        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('supplierPhone') ? document.getElementById('supplierPhone').innerHTML = this.supplierPhone : ''
        document.getElementById('supplierFax') ? document.getElementById('supplierFax').innerHTML = this.supplierFax : ''
        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 tr = []
        for (let i = 0; i < this.tableData1.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>'
          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[3].innerHTML = this.tableData1[j].图号
            document.getElementsByClassName('tableData')[j].children[4].innerHTML = this.tableData1[j].名称
            document.getElementsByClassName('tableData')[j].children[5].innerHTML = this.tableData1[j].规格
            document.getElementsByClassName('tableData')[j].children[6].innerHTML = this.tableData1[j].数量
            this.hasTax === '含税' ? document.getElementsByClassName('tableData')[j].children[7].innerHTML = this.tableData1[j].含税单价 : document.getElementsByClassName('tableData')[j].children[7].innerHTML = this.tableData1[j].未税单价
            document.getElementsByClassName('tableData')[j].children[8].innerHTML = (Number(document.getElementsByClassName('tableData')[j].children[7].innerHTML) * Number(this.tableData1[j].数量)).toFixed(2)
            this.tableData1[j].交货期 ? document.getElementsByClassName('tableData')[j].children[9].innerHTML = this.tableData1[j].交货期.split(' ')[0] : document.getElementsByClassName('tableData')[j].children[9].innerHTML = ''
            document.getElementsByClassName('tableData')[j].children[10].innerHTML = this.tableData1[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 : ''
        this.contentNew = document.getElementsByClassName('editor-content')[0].innerHTML
        this.$refs.tinymce.initTinymce()
      } else {
        this.$message.warning('请先选择合同进行调整')
      }
    },
    demo2() {
      this.content = `demo2`
    },
    demo3() {
      this.content = `demo3`
    },
    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
      for (let i = 0; i < this.tableData1.length; i++) {
        this.组件零件流水号组.push(this.tableData1[i].组件零件流水号)
        this.组件零件基本件流水号组.push(this.tableData1[i].组件零件基本件流水号)
        this.数量组.push(this.tableData1[i].数量)
        this.hasTax === '含税' ? this.单价组.push(this.tableData1[i].含税单价) : this.单价组.push(this.tableData1[i].未税单价)
        this.交货期组.push(this.tableData1[i].交货期)
      }
      if (this.contractNumValue) {
        this.$confirm('此采购合同将递交审批，递交后该合同不可删除，确认完成编辑？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log(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)
          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).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('请先选择合同进行编辑')
      }
    }
  }
}
</script>

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