<!--
  @description: 验收-新增、编辑
  @author: 郝定康
  @routerPath:
  @date： 2021-10-26 18:15:57
-->
<template>
  <el-dialog
    v-dialogDrag
    :visible.sync="dialogData.dialog"
    :before-close="close"
    :lock-scroll="false"
    append-to-body
    width="1000px"
    title="验收"
  >
    <div class="p0-16 mb10">
      <p class="page-title">
        1.合同信息
      </p>
      <table class="tableData">
        <tr>
          <td>
            合同编号
          </td>
          <td>
            {{ dialogData.contractNo }}
          </td>
          <td>
            合同名称
          </td>
          <td colspan="3">
            {{ dialogData.contractName }}
          </td>
        </tr>
      </table>
      <el-form
        ref="form"
        :model="formData"
        :rules="rules"
        :inline-message="true"
      >
        <p class="page-title">
          2.验收行项目
          <el-button type="primary" @click="lineItemAdd">
            选择行项目
          </el-button>
        </p>
        <el-table
          ref="smallTable"
          :data="formData.checkDetailInfos"
          highlight-current-row
        >
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="50"
          />
          <el-table-column
            prop="productNo"
            label="产品编码"
            align="center"
          />
          <el-table-column
            prop="productName"
            label="产品名称"
            align="center"
          />
          <el-table-column
            prop="quantity"
            label="成交数量"
            align="center"
          />
          <el-table-column
            prop="price"
            label="含税单价（元）"
            align="center"
          />
          <el-table-column
            prop="checkQuantity"
            label="验收数量"
            align="center"
          >
            <template slot-scope="scope">
              <el-form-item
                show-word-limit
                :prop="'checkDetailInfos.' + scope.$index + '.checkQuantity'"
                :rules="rules.checkQuantity"
              >
                <money
                  :thousands="false"
                  :unit-fixed="6"
                  :money-value="scope.row"
                  width="110px"
                  name="checkQuantity"
                  style="display: inline-block;"
                  @input="checkQuantityChange(scope.row)"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="checkPrice"
            label="验收总价（元）"
            align="center"
          />
          <!-- <template slot-scope="scope">
              <el-form-item
                show-word-limit
                :prop="'checkDetailInfos.' + scope.$index + '.checkPrice'"
                :rules="rules.checkPrice"
              >
                <money
                  :thousands="true"
                  :unit-fixed="6"
                  :money-value="scope.row"
                  width="110px"
                  name="checkPrice"
                  style="display: inline-block;"
                />
              </el-form-item>
            </template> -->
          <!-- </el-table-column> -->
          <!-- 操作 -->
          <el-table-column
            label="操作"
            width="100"
            header-align="center"
            align="center"
          >
            <template slot-scope="scope">
              <el-link
                type="primary"
                @click="lineItemDel(scope.$index)"
              >
                移除
              </el-link>
            </template>
          </el-table-column>
        </el-table>
        <p class="page-title">
          3.申请验收信息
        </p>
        <table class="from_table">
          <tr>
            <td>
              <el-form-item
                show-word-limit
                label="是否付款"
                prop="isPayType"
              />
            </td>
            <td colspan="3">
              <el-radio-group v-model="formData.isPayType" @change="isPayTypeChange">
                <el-radio v-for="(item,index) in isPayTypeList" :key="index" :label="item.typecode">
                  {{ item.typename }}
                </el-radio>
              </el-radio-group>
            </td>
          </tr>
          <tr v-if="formData.isPayType === '01'">
            <td>
              <el-form-item
                show-word-limit
                label="付款阶段"
                prop="payStageId"
              />
            </td>
            <td>
              <el-select v-model="formData.payStageId" filterable placeholder="请选择" @change="paymentStageChange">
                <el-option
                  v-for="(item) in getPaymentStageList"
                  :key="item.typecode"
                  :label="item.typename"
                  :value="item.typecode"
                />
              </el-select>
            </td>
            <td>
              <el-form-item
                show-word-limit
                label="付款阶段总额"
              />
            </td>
            <td>
              {{ formData.checkTotalPrice ? moneyFormat(formData.checkTotalPrice.toFixed(6)) : '' }}
            </td>
          </tr>
          <tr>
            <td>
              <el-form-item
                show-word-limit
                label="验收阶段"
                prop="checkStage"
              />
            </td>
            <td colspan="3">
              <gx-input
                v-model="formData.checkStage"
                gx-maxlength="varchar200"
              />
            </td>
          </tr>
          <tr>
            <td>
              <el-form-item
                show-word-limit
                label="验收名称"
                prop="checkName"
              />
            </td>
            <td>
              <gx-input
                v-model="formData.checkName"
                gx-maxlength="varchar200"
              />
            </td>
            <td>
              <el-form-item
                show-word-limit
                label="验收编号"
                prop="checkNo"
              />
            </td>
            <td>
              <gx-input
                v-model="formData.checkNo"
                gx-maxlength="varchar200"
              />
            </td>
          </tr>
          <tr>
            <td>
              <el-form-item
                show-word-limit
                label="验收人"
                prop="checkUserRealName"
              />
            </td>
            <td>
              <gx-input
                v-model="formData.checkUserRealName"
                gx-maxlength="varchar200"
              />
            </td>
            <td>
              <el-form-item
                show-word-limit
                label="参与人"
                prop="participantRealName"
              />
            </td>
            <td>
              <gx-input
                v-model="formData.participantRealName"
                gx-maxlength="varchar200"
              />
            </td>
          </tr>
          <tr>
            <td>
              <el-form-item
                show-word-limit
                label="验收描述"
                prop="checkDesc"
              />
            </td>
            <td colspan="3">
              <gx-input
                v-model="formData.checkDesc"
                gx-maxlength="varchar200"
              />
            </td>
          </tr>
          <tr>
            <td>
              <el-form-item
                show-word-limit
                label="时间"
                prop="checkTime"
              />
            </td>
            <td colspan="3">
              <el-date-picker
                v-model="formData.checkTime"
                :picker-options="disabledPickerOptions"
                :format="elValueSaveFormat"
                :value-format="elValueSaveFormat"
                :default-time="defaultTimeDateTime"
                type="datetime"
                placeholder="请选择日期"
              />
            </td>
          </tr>
          <tr>
            <td>
              <el-form-item
                show-word-limit
                label="附件列表"
                prop="contractCheckFile"
              />
            </td>
            <td colspan="3">
              <upload
                ref="upload"
                :title="''"
                :data="contract_check_file"
                :auto-delete="true"
                :auto-upload="true"
                :file-size="200"
                tip-text="上传附件格式.doc，.docx，.pdf，.jpg"
                accept=".doc,.docx,.pdf,.jpg"
                file-ref="fileRef"
                but-text="上传文件"
                :on-change="contractCheckFileChange"
              />
            </td>
          </tr>
        </table>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="save('00')">
        保存
      </el-button>
      <el-button type="primary" @click="save('01')">
        提交
      </el-button>
      <el-button @click="close">
        取消
      </el-button>
    </span>
    <acceptanceLineItemInfoDialog v-if="lineItemInfoDialogData.dialog" :dialog-data="lineItemInfoDialogData" @lineItemSelect="lineItemSelect" />
  </el-dialog>
</template>

<script>
/* api */
import { queryContractCheckStageById, saveContractCheckStageData, listContractPayStage } from '@/api/contractManagement/index'
/* 公共混入*/
import { contractSigningMixins } from '../mixins/contractSigningMixins'
import { contractSigningMixin } from '../mixins/contractSigningMixin'
/* 公共方法 */
import { randomData, restoreInitialValue, moneyFormat } from '@assets/js/utils' // 常用方法
import { characters1_auto } from '@/assets/js/validate'// 校验输入内容
/* 公共组件*/
import money from '@comp/common/money/money' // 数字组件
import upload from '@comp/common/updownload/upload' // 文件上传组件
import acceptanceLineItemInfoDialog from './acceptanceLineItemInfo-dialog' // 选择行项目
export default {
  name: 'AcceptanceAddDialog',
  components: {
    money,
    upload,
    acceptanceLineItemInfoDialog
  },
  mixins: [contractSigningMixin, contractSigningMixins],
  props: {
    dialogData: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      getPaymentStageList: [],
      formData: {
        isPayType: '01', // 是否付款
        payStageId: '', // 付款阶段id
        payStageName: '', // 付款阶段名称
        checkTotalPrice: '', // 付款阶段金额
        checkDesc: '', // 验收描述
        checkName: '', // 验收名称
        checkNo: '', // 验收编号
        checkStage: '', // 验收
        checkTime: '', // 验收时间
        checkUserRealName: '', // 验收人名称
        contractId: '', // 合同id
        id: '',
        participantRealName: '', // 参与人名称
        checkDetailInfos: [],
        contractCheckFile: '', // 附件列表
        status: '' // 00保存 01提交
      },
      lineItemInfoDialogData: {
        dialog: false,
        id: '',
        ids: ''
      },
      isPayTypeList: [{ typecode: '01', typename: '是' }, { typecode: '00', typename: '否' }],
      rules: {
        isPayType: [{ required: true, message: '请选择', trigger: 'blur' }], // 是否付款
        payStageId: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 付款阶段
        checkDesc: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 验收描述
        checkName: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 验收名称
        checkNo: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 验收编号
        checkStage: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 验收
        checkTime: [{ required: true, message: '请选择', trigger: 'blur' }], // 验收时间
        participantRealName: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 参与人名称
        checkUserRealName: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 验收人名称
        contractCheckFile: [{ required: true, message: '请选择', trigger: 'blur' }], // 附件列表
        checkQuantity: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 数量
        checkPrice: [{ required: true, validator: characters1_auto, trigger: 'blur' }] // 验收总价（元）
      }
    }
  },
  watch: {
    'dialogData.dialog'(val) {
      // 打开弹框加载数据
      if (val) {
        restoreInitialValue(this.formData)
        this.getPaymentStage(this.dialogData.contractId)
        window.console.log(this.dialogData)
        if (this.dialogData.id) {
          this.initData()
        } else {
          this.contract_check_file.bizId = this.formData.id = randomData()
        }
      }
    }
  },
  created() {
  },
  methods: {
    moneyFormat,
    // 是否付款
    isPayTypeChange() {
      this.formData.payStageId = '' // 付款阶段id
      this.formData.payStageName = '' // 付款阶段名称
      this.formData.checkTotalPrice = '' // 付款阶段金额
    },
    // 行项目验收总价
    checkQuantityChange(item) {
      item.checkPrice = item.price * item.checkQuantity
    },
    // 付款阶段
    paymentStageChange(data) {
      this.getPaymentStageList.forEach(item => {
        if (item.typecode === data) {
          this.formData.payStageName = item.typename // 付款阶段名称
          this.formData.checkTotalPrice = item.paymentMoney // 付款阶段金额
        }
      })
    },
    // 付款阶段
    getPaymentStage(contractId) {
      this.getPaymentStageList = []
      const params = {
        contractId, // 合同id
        checkFlag: '01' // 过滤已选择
      }
      // 获取付款阶段
      listContractPayStage(params).then(res => {
        res.data.stageDetailDtoList.forEach(item => {
          this.getPaymentStageList.push({
            typecode: item.id,
            typename: item.paymentName,
            paymentMoney: item.paymentMoney
          })
        })
      })
    },
    // 选择行项目
    lineItemAdd() {
      const idsArr = []
      this.formData.checkDetailInfos.forEach(item => {
        idsArr.push(item.checkDetailId)
      })
      // 已选行项目id集合
      this.lineItemInfoDialogData.ids = idsArr.join(',')
      // 合同id
      this.lineItemInfoDialogData.id = this.dialogData.contractId
      this.lineItemInfoDialogData.dialog = true
    },
    // 行项目选择回调
    lineItemSelect(data) {
      data.forEach(item => {
        this.formData.checkDetailInfos.push({
          productNo: item.productNo, // 产品编码
          productName: item.productName, // 产品名称
          quantity: item.quantity, // 成交数量
          price: item.price, // 含税单价（元）
          checkDetailId: item.id,
          checkPrice: '', // 验收总价（元）
          checkQuantity: '' // 验收数量
        })
      })
    },
    // 删除验收行项目
    lineItemDel(index) {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtn',
        cancelButtonClass: 'cancelBtn',
        type: 'warning'
      }).then(() => {
        this.formData.checkDetailInfos.splice(index, 1)
      }).catch(() => {
      })
    },
    // 附件列表
    contractCheckFileChange(file, fileList) {
      if (fileList.length > 0) {
        this.$set(this.formData, 'contractCheckFile', 'true') // 上传了
      } else {
        this.$set(this.formData, 'contractCheckFile', '') // 未上传
      }
    },
    initData() {
      queryContractCheckStageById(this.dialogData.id, '').then(res => {
        this.formData = res.data
        this.contract_check_file.bizId = this.formData.id
      })
    },
    // 取消
    close() {
      this.$emit('callback')
      this.dialogData.dialog = false
    },
    save(type) {
      if (type === '01') {
        let validate = false
        this.$refs['form'].validate((valid) => {
          if (valid) {
            validate = true
          } else {
            validate = false
            this.$message({
              message: '请注意页面提示',
              type: 'warning'
            })
          }
        })
        if (!validate) {
          return false
        }
        // 行项目校验
        if (!this.formData.checkDetailInfos.length) {
          this.$message({
            message: '请选择验收行项目',
            type: 'warning'
          })
        }
        let lumpSum = 0
        this.formData.checkDetailInfos.forEach(item => {
          lumpSum += item.price * item.checkQuantity
        })
        if (lumpSum > this.formData.checkTotalPrice && this.formData.isPayType === '01') {
          this.$message({
            message: '行项目验收总价之和不能大于付款阶段总额',
            type: 'warning'
          })
          return false
        }
      }
      this.formData.status = type
      this.formData.contractId = this.dialogData.contractId
      saveContractCheckStageData(this.formData).then(res => {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        this.close()
      })
    }
  }
}
</script>

<style scoped lang="less">
</style>
