<template>
  <div class="app-container">
    <el-card>
      <el-form ref="form1" :model="form1" label-position="right" label-width="110px" class="searchForm">
        <el-row>
          <el-col :span="6">
            <el-form-item label="合同号">
              <el-select v-model="contractNumValue" placeholder="合同号" filterable clearable size="small" @change="stipulateArrivalTime='';searchTable1()">
                <el-option
                  v-for="item in contractNum"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                  <div style="float: left">{{ item.label }}</div>
                  <div style="float: right; color: #8492a6; font-size: 13px">{{ item.supplierName }}</div>
                </el-option>
              </el-select>
            </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="6">
            <el-form-item label="规定到货时间">
              <el-date-picker
                v-model="stipulateArrivalTime"
                :picker-options="endDateOpt"
                :disabled="Boolean(!contractNumValue)"
                size="small"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                @change="searchDemo();calcDay()"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="付款方式">
              <el-select v-model="payMethodValue" placeholder="付款方式" size="small" @change="searchDemo();payMethodChange()">
                <el-option
                  v-for="item in payMethod"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="第1次付款时间">
              <el-select v-model="payTime1Value" placeholder="请选择" size="small">
                <el-option
                  v-for="item in payTime"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="第2次付款时间">
              <el-select v-model="payTime2Value" :disabled="disable2" placeholder="请选择" size="small">
                <el-option
                  v-for="item in payTime"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="第3次付款时间">
              <el-select v-model="payTime3Value" :disabled="disable3" placeholder="请选择" size="small">
                <el-option
                  v-for="item in payTime"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="第4次付款时间">
              <el-select v-model="payTime4Value" :disabled="disable4" placeholder="请选择" size="small">
                <el-option
                  v-for="item in payTime"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="第5次付款时间">
              <el-select v-model="payTime5Value" :disabled="disable5" placeholder="请选择" size="small">
                <el-option
                  v-for="item in payTime"
                  :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="freight" size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="税率">
              <el-input v-model="taxRate" size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="币种">
              <el-select v-model="currencyValue" placeholder="币种" size="small">
                <el-option
                  v-for="item in currency"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card>
      <el-table v-loading="" :data="tableData1" border style="width: 100%;max-height: 300px;" height="300px" size="mini">
        <el-table-column label="参考价格" align="center" width="100">
          <template slot-scope="scope">
            {{ scope.row.参考价格 }}
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" width="100">
          <template slot-scope="scope">
            <el-input v-model="scope.row.最低单价" size="mini" style="width:70px"/>
          </template>
        </el-table-column>
        <el-table-column label="发货天数" align="center" width="100">
          <template slot-scope="scope">
            <el-input v-model="deliveryDay[scope.$index]" size="mini" style="width:70px"/>
          </template>
        </el-table-column>
        <el-table-column label="物料计划到货时间" align="center" width="150">
          <template slot-scope="scope">
            {{ scope.row.物料计划到货时间.split(' ')[0] }}
          </template>
        </el-table-column>
        <el-table-column label="物料名称" align="center" min-width="200">
          <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" width="200">
          <template slot-scope="scope">
            {{ scope.row.零件数量 }}
          </template>
        </el-table-column>
        <el-table-column label="订货数量" align="center" width="100">
          <template slot-scope="scope">
            {{ scope.row.订货数量 }}
          </template>
        </el-table-column>
        <el-table-column label="金额" align="center" width="100">
          <template slot-scope="scope">
            {{ scope.row.金额 }}
          </template>
        </el-table-column>
      </el-table>
      <el-button
        type="primary"
        size="small"
        icon=""
        style="margin-top:10px"
        @click="calculateContractSum">计算合同总额</el-button>
      <span>合同总额:</span>
      <el-input v-model="contractSum" size="small" readonly/>
    </el-card>

    <el-card>
      <el-table
        :data="tableData2"
        :show-header="false"
        highlight-current-row
        border
        height="280px"
        style="width: 250px;display:inline-block;max-height: 280px;"
        size="mini"
        @row-click="searchDemo">
        <el-table-column align="center" label="合同模板名称">
          <template slot-scope="scope">
            {{ scope.row.合同模板名称 }}
          </template>
        </el-table-column>
      </el-table>
      <el-input :rows="20" v-model="textArea" type="textarea" style="width:calc(99% - 250px);float:right;margin-bottom: 20px" resize="none"/>
      <!--将新一般处理页添加至通讯服务器-->
      <el-upload
        ref="upload"
        :before-upload="beforeUpload"
        :file-list="fileList"
        :auto-upload="false"
        style="display: inline-block;width:250px"
        class="upload-demo"
        action="http://localhost:8022/submit/uploadFile0.ashx"
        list-type="picture">
        <el-button slot="trigger" size="small" type="primary" style="margin:10px 10px 0 10px">添加图纸附件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">生成采购合同</el-button>
      </el-upload>
    </el-card>
    <!--<el-button style="margin-left: 10px;" size="small" type="success" @click="test">test</el-button>-->
  </div>
</template>

<script>
import { searchInquirySheet, searchSheetContract, initPayMethod, initPayTimeNode, searchContractDemo, doneContract, insertFile } from '@/api/PurchasingCenter/CreateContract'
import { mapGetters } from 'vuex'

export default {
  inject: ['reload'],
  data() {
    return {
      fileName: '',
      hasFile: 0,
      searchView: '',
      fileList: [],
      minDate: null,
      endDateOpt: { // 禁用大于规定到货日期和小于当前日期
        disabledDate: (time) => {
          if (this.minDate) {
            return time.getTime() > this.minDate || time.getTime() < new Date()
          }
        }
      },
      form1: {},
      contractNumValue: '', // 合同流水号
      contractNum: [],
      contractNameNum: '', // 合同编号/询价单号
      contractName: '产品购销合同', // 合同名称
      supplierName: '', // 供应商名称
      stipulateArrivalTime: '', // 规定到货时间
      payMethodValue: 1, // 付款方式流水号
      payMethodName: '', // 付款方式名称
      payMethod: [],
      payTime: [],
      payTime1Value: 1, // 付款时间
      payTime2Value: 1, // 付款时间
      payTime3Value: 1, // 付款时间
      payTime4Value: 1, // 付款时间
      payTime5Value: 1, // 付款时间
      payTime6Value: 1, // 付款时间
      freight: 0, // 运费
      taxRate: '0.17', // 税率
      currencyValue: 1, // 币种
      currency: [
        {
          label: '人民币',
          value: 1
        }, {
          label: '美元',
          value: 2
        }, {
          label: '英镑',
          value: 3
        }, {
          label: '欧元',
          value: 4
        }
      ], // 币种
      calculateWayValue: [], // 计算方式（不要了）
      calculateWay: [
        {
          label: '个数',
          value: 1
        }, {
          label: '重量',
          value: 2
        }
      ],
      weight: [], // 重量（不要了）
      disable2: true,
      disable3: true,
      disable4: true,
      disable5: true,
      disable6: true,
      tableData1: [], // 物料表
      contractSum: '', // 合同总额
      deliveryDay: [], // 发货天数
      tableData2: [], // 合同模板表
      textArea: '',
      paramRow: '', // 参数row
      materialGroup: '', // 物料流水号组
      numberGroup: '', // 数量组
      priceGroup: '', // 单价组
      dayGroup: '', // 发货天数组
      payGroup: '', // 付款方式组
      planGroup: '', // 计划付款时间组
      taxGroup: '', // 税率组
      currencyGroup: '', // 币种组
      groupPartGroup: '', // 组件零件流水号组
      calculateWayGroup: '', // 计算方式组（不要了）
      weightGroup: '', // 重量组（不要了）
      supplierValue: '',
      groupNum1: [] // 防止渲染不出来的中间变量
    }
  },
  computed: {
    ...mapGetters([
      'sidebar',
      'avatar',
      'name',
      'id'
    ])
  },
  created() {
    this.fetchData()
  },
  methods: {
    test() {
      this.$refs.upload.submit() // 图片传本地
    },
    beforeUpload(file) { // 传成功前
      this.fileName = file.name
    },
    submitUpload() { // 生成采购合同+传图片附件
      for (let i = 0; i < this.contractNum.length; i++) { // 在生成合同处也有
        if (this.contractNum[i].value === this.contractNumValue) {
          this.contractNameNum = this.contractNum[i].label // 获取询价单号
          this.supplierValue = this.contractNum[i].supplierValue // 获取供应商流水号
        }
      }
      this.$refs.upload.submit() // 图片传本地
      if (this.fileName !== '') { // 有附件，先向数据库中插入一条记录（记录合同编号及文件名）
        insertFile(this.fileName, this.contractNameNum).then(response => {
          if (response.data[0].result === '1') {
            this.doneContract()
          } else {
            this.$message.error('附件名插入数据库失败')
          }
        })
      } else { // 无附件，直接执行生成合同
        this.doneContract()
      }
      this.contractNameNum = ''
      this.fileName = ''
    },
    fetchData() {
      searchInquirySheet(0, 0, 0, 0, 1, this.id).then(response => { // 初始化询价单号
        for (let i = 0; i < response.data.length; i++) {
          this.contractNum.push({
            value: response.data[i].询价单流水号,
            label: response.data[i].询价单编号,
            supplierName: response.data[i].供应商名称,
            supplierValue: response.data[i].供应商流水号
          })
        }
      })
      searchContractDemo().then(response => { // 初始化合同模板
        this.tableData2 = response.data
      })
      initPayMethod().then(response => { // 初始化付款方式
        for (let i = 0; i < response.data.length; i++) {
          this.payMethod.push({
            label: response.data[i].付款方式内容,
            value: response.data[i].付款方式流水号
          })
        }
      })
      initPayTimeNode().then(response => {
        for (let i = 0; i < response.data.length; i++) {
          if (parseInt(response.data[i].付款时间节点流水号) !== 0) {
            this.payTime.push({
              label: response.data[i].付款时间节点名称,
              value: response.data[i].付款时间节点流水号
            })
          }
        }
      })
    },
    payMethodChange() { // 付款方式改变
      for (let i = 0; i < this.payMethod.length; i++) {
        if (this.payMethod[i].value === this.payMethodValue) {
          this.payMethodName = this.payMethod[i].label
        }
      }
      const payTimeNum = this.payMethodName.split(':')
      switch (payTimeNum.length) {
        case 1:
          this.disable2 = true
          this.disable3 = true
          this.disable4 = true
          this.disable5 = true
          this.disable6 = true
          break
        case 2:
          this.disable2 = false
          this.disable3 = true
          this.disable4 = true
          this.disable5 = true
          this.disable6 = true
          break
        case 3:
          this.disable2 = false
          this.disable3 = false
          this.disable4 = true
          this.disable5 = true
          this.disable6 = true
          break
        case 4:
          this.disable2 = false
          this.disable3 = false
          this.disable4 = false
          this.disable5 = true
          this.disable6 = true
          break
        case 5:
          this.disable2 = false
          this.disable3 = false
          this.disable4 = false
          this.disable5 = false
          this.disable6 = true
          break
        case 6:
          this.disable2 = false
          this.disable3 = false
          this.disable4 = false
          this.disable5 = false
          this.disable6 = false
          break
      }
    },
    searchTable1() {
      const numGroup = [] // 空数组，放物料的计划到货时间
      searchSheetContract(this.contractNumValue).then(response => {
        this.tableData1 = response.data
        this.calcDay() // 先给表置0
        for (let i = 0; i < response.data.length; i++) {
          this.tableData1[i].金额 = parseFloat(this.tableData1[i].最低单价) * parseFloat(this.tableData1[i].订货数量)
          numGroup.push(Date.parse(this.tableData1[i].物料计划到货时间))
        }
        this.minDate = new Date(Math.min(...numGroup))
      }).then(() => {
        this.groupNum1 = this.tableData1 // 给中间变量，需要时重新push
      })
      this.calcDay() // 先给表置0
    },
    searchDemo(row = this.paramRow) {
      for (let i = 0; i < this.payMethod.length; i++) {
        if (this.payMethod[i].value === this.payMethodValue) {
          this.payMethodName = this.payMethod[i].label
        }
      }
      this.paramRow = row
      searchContractDemo(this.paramRow.合同模板流水号).then(response => {
        this.textArea = response.data[0].合同模板内容.replace('stipulateArrivalTime', this.stipulateArrivalTime).replace('payMethodName', this.payMethodName)
      })
    },
    calcDay() { // 计算发货天数
      this.deliveryDay = []
      for (let i = 0; i < this.tableData1.length; i++) {
        this.stipulateArrivalTime
          ? (this.deliveryDay[i] = parseInt((Date.parse(this.stipulateArrivalTime) - new Date()) / (1000 * 60 * 60 * 24)))
          : (this.deliveryDay[i] = 0)
      }
    },
    calculateContractSum() {
      this.contractSum = 0
      this.tableData1 = []
      for (let i = 0; i < this.groupNum1.length; i++) {
        this.groupNum1[i].金额 = parseFloat(this.groupNum1[i].最低单价) * parseFloat(this.groupNum1[i].订货数量)
        this.contractSum += parseFloat(this.groupNum1[i].金额)
        this.tableData1.push(this.groupNum1[i])
      }
    },
    doneContract() { // 生成采购合同
      for (let i = 0; i < this.contractNum.length; i++) {
        if (this.contractNum[i].value === this.contractNumValue) {
          this.contractNameNum = this.contractNum[i].label // 获取询价单号
          this.supplierValue = this.contractNum[i].supplierValue // 获取供应商流水号
        }
      }
      if (this.contractNum === '' || this.contractNum === null) {
        this.$message.error('请选择生成合同的询价单')
      } else if (this.stipulateArrivalTime === '' || this.stipulateArrivalTime === null) {
        this.$message.error('请选择规定到货时间！')
      } else {
        for (let i = 0; i < this.deliveryDay.length; i++) {
          if (parseInt(this.deliveryDay[i]) < 0) {
            this.$message.error('规定到货日期不可小于当前日期')
            return
          }
        }
        this.materialGroup = ''
        this.numberGroup = ''
        this.priceGroup = ''
        this.dayGroup = ''
        this.payGroup = ''
        this.planGroup = ''
        this.taxGroup = ''
        this.currencyGroup = ''
        this.groupPartGroup = ''
        for (let i = 0; i < this.tableData1.length; i++) {
          this.materialGroup += this.tableData1[i].物料流水号 + ','
          this.numberGroup += this.tableData1[i].订货数量 + ','
          this.priceGroup += this.tableData1[i].最低单价 + ','
          this.dayGroup += this.deliveryDay[i] + ','
          this.taxGroup += this.taxRate + ','
          this.currencyGroup += this.currencyValue + ','
          this.groupPartGroup += this.tableData1[i].组件零件流水号 + ',' // fucking
        }
        for (let i = 0; i < this.payMethod.length; i++) {
          if (this.payMethod[i].value === this.payMethodValue) {
            this.payMethodName = this.payMethod[i].label
          }
        }
        const payTimeNum = this.payMethodName.split(':')
        if (payTimeNum.length > 1) {
          for (let i = 0; i < payTimeNum.length; i++) {
            switch (i) {
              case 0:
                this.planGroup += this.payTime1Value + ','
                break
              case 1:
                this.planGroup += this.payTime2Value + ','
                break
              case 2:
                this.planGroup += this.payTime3Value + ','
                break
              case 3:
                this.planGroup += this.payTime4Value + ','
                break
              case 4:
                this.planGroup += this.payTime5Value + ','
                break
              case 5:
                this.planGroup += this.payTime6Value + ','
                break
            }
            this.payGroup += payTimeNum[i] + ',' // 付款比例 付款方式 付款计划
          }
        } else {
          this.payGroup = '10,' // 付款比例 付款方式 付款计划
          this.planGroup = this.payTime1Value + ',' // 付款时间
        }
        this.materialGroup = this.materialGroup.substr(0, this.materialGroup.length - 1)
        this.numberGroup = this.numberGroup.substr(0, this.numberGroup.length - 1)
        this.priceGroup = this.priceGroup.substr(0, this.priceGroup.length - 1)
        this.dayGroup = this.dayGroup.substr(0, this.dayGroup.length - 1)
        this.payGroup = this.payGroup.substr(0, this.payGroup.length - 1)
        this.planGroup = this.planGroup.substr(0, this.planGroup.length - 1)
        this.taxGroup = this.taxGroup.substr(0, this.taxGroup.length - 1)
        this.currencyGroup = this.currencyGroup.substr(0, this.currencyGroup.length - 1)
        this.groupPartGroup = this.groupPartGroup.substr(0, this.groupPartGroup.length - 1)
        doneContract(this.contractNameNum, this.contractName, this.stipulateArrivalTime, this.stipulateArrivalTime, this.payMethodName, this.supplierValue, this.textArea, this.freight, this.materialGroup, this.numberGroup, this.priceGroup, this.dayGroup, this.payGroup, this.planGroup, this.taxGroup, this.currencyGroup, this.calculateWayGroup, this.weightGroup, this.id, this.groupPartGroup).then(response => {
          if (response.data[0].result === '1') {
            this.$message.success('生成合同成功')
            this.reload()
          } else { this.$message.error('生成合同失败') }
        })
      }
    }
  }
}
</script>

<style scoped>
  .el-card{
    margin-bottom: 15px;
  }
  .el-date-editor{
    width:200px
  }
  .el-select{
    width:200px
  }
  .el-input{
    width:200px
  }
  span{
    margin: 10px 0 10px 10px;
  }
  .searchForm .el-form-item{
    margin-bottom: 5px;
  }
</style>
