<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
	  draggable
      width="1200px"
      height="500px"
      @close="close"
      v-model="visible">
      <el-row>
        <el-row>
          <el-col :span="24">

            <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="method==='view'"
                     label-width="135px" @submit.native.prevent>
              <el-row  :gutter="15">
                <el-col :span="12">
                  <el-form-item label="报告文号" prop="reportNo"
                                :rules="[

                   ]">
                    <el-input :readonly="true" @focus="openContractForm()" v-model="inputForm.reportNo" placeholder="请填写报告文号">
                      	<template #append>
							<el-button icon="el-icon-search" @click="openContractForm()"></el-button>
						</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目名称" prop="projectName"
                                :rules="[
                   ]">
                    <el-input :disabled="true" v-model="inputForm.projectName" placeholder="请填写项目名称" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="报告主办人" prop="reportSponsor"
                                :rules="[
                   ]">
                    <el-input :disabled="true" v-model="inputForm.reportSponsor" placeholder="请填写报告主办人" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目经理1" prop="projectMasterName"
                                :rules="[
                   ]">
                    <el-input :disabled="true" v-model="inputForm.projectMasterName" placeholder="请填写项目经理1" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目经理2" prop="projectMaster2Name"
                                :rules="[
                   ]">
                    <el-input :disabled="true" v-model="inputForm.projectMaster2Name" placeholder="请填写项目经理2" clearable></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="创建人" prop="createBy.name"
                                :rules="[
                   ]">
                    <el-input :disabled="true" v-model="inputForm.createBy.name" placeholder="请填写创建人" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="创建时间" prop="createDate"
                                :rules="[
                   ]">
                    <el-input :disabled="true" v-model="inputForm.createDate" placeholder="请填写创建时间" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="作废原因" prop="cancellateReason"
                                :rules="[
                   ]">
                    <el-input v-model="inputForm.cancellateReason" placeholder="请填写作废原因" clearable></el-input>
                  </el-form-item>
                </el-col>

              </el-row>
            </el-form>
          </el-col>
        </el-row>
      </el-row>
		<template #footer>
			<span class="dialog-footer">
			  <el-button @click="close()" icon="el-icon-circle-close">关闭</el-button>
			  <el-button v-if="method === 'edit'" type="primary" icon="el-icon-circle-check" @click="doSubmit('save')">确定</el-button>
			</span>
		</template>

      <ReportCancellApplyChooseCom  ref="reportCancellApplyChooseCom" @getProject="getContract"></ReportCancellApplyChooseCom>
    </el-dialog>
  </div>
</template>

<script>
  import ReportCancellApplyService from '@/api/cw/reportCancellApply/ReportCancellApplyService'
  import projectReportService from '@/api/cw/reportManagement/ProjectReportService'
  import ReportCancellApplyChooseCom from './ReportCancellApplyChooseCom'
  export default {
    props: {
      businessId: {
        type: String,
        default: ''
      },
      formReadOnly: {
        type: Boolean,
        default: false
      },
      status: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        title: '',
        method: '',
        loading: false,
        inputForm: {
          projectId: '',
          reportNewLineId: '',
          id: '',
          createDate: '',
          createBy: {
            id: '',
            name: this.$store.state.user.name
          },
          remarks: '',
          reportNo: '',
          projectName: '',
          cancellateReason: '',
          reportSponsor: '',
          projectMasterName: '',
          projectMaster2Name: '',
          cwFileInfoList: [],
          servedUnitId: '',
          status: ''
        },
        keyWatch: '',
        activeName: 'newRow',
        tableKey: '',
        tableKeyClient: '1',
        visible: false
      }
    },
    ReportCancellApplyService: null,
    created () {
      this.reportCancellApplyService = new ReportCancellApplyService()
    },
    computed: {
      bus: {
        get () {
          return this.businessId
        },
        set (val) {
          this.businessId = val
        }
      }
    },
    watch: {
      'keyWatch': {
        handler (newVal) {
          if (this.commonJS.isNotEmpty(this.bus)) {
            this.init('', this.bus)
          } else {
            this.$nextTick(() => {
              this.$refs.inputForm.resetFields()
            })
          }
        }
      }
    },
    components: {
      ReportCancellApplyChooseCom
    },
    methods: {
      openContractForm () {
        if (!this.commonJS.isEmpty(this.inputForm.contractId)) {
          this.$refs.reportCancellApplyChooseCom.init()
        } else {
          this.$refs.reportCancellApplyChooseCom.init()
        }
      },
      getUpload (p, index) {
        p.then((list) => {
          // list为返回数据
          this.inputForm.cwProjectInfoList[index].cwFileInfoList = list
          this.inputForm.cwProjectInfoList[index].fileNumber = list.length
          this.tableKeyClient = Math.random()
          // console.log('this.inputForm.cwFileInfoList', this.inputForm.cwFileInfoList)
          // console.log('list.length', list.length)
          // console.log(list)
        })
      },
      getKeyWatch (keyWatch) {
        this.keyWatch = keyWatch
      },
      init (method, id) {
        this.visible = true
        if (method === 'edit') {
          this.title = '项目信息修改'
          this.method = method
        } else {
          this.title = '项目详情'
          this.method = 'view'
        }
        this.activeName = 'newRow'
        this.reportCancellApplyService = new ReportCancellApplyService()
        this.method = method
        this.inputForm = {
          projectId: '',
          reportNewLineId: '',
          id: '',
          createDate: '',
          createBy: {
            id: '',
            name: this.$store.state.user.name
          },
          remarks: '',
          reportNo: '',
          projectName: '',
          cancellateReason: '',
          reportSponsor: '',
          projectMaster2Name: '',
          projectMasterName: ''
        }
        this.inputForm.id = id
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          this.loading = true
          this.reportCancellApplyService.queryById(this.inputForm.id).then(({data}) => {
            this.inputForm = this.recover(this.inputForm, data)
            this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
            if (this.commonJS.isEmpty(this.inputForm.createDate)) {
              this.inputForm.createDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
            }
            this.loading = false
          })
        })
      },
      saveForm (callback) {
        this.doSubmit('save', callback)
      },
      startForm (callback) {
        this.doSubmit('start', callback)
      },
      async agreeForm (callback) {
        await this.reportCancellApplyService.queryById(this.inputForm.id).then(({data}) => {
          if (this.inputForm.status !== '2') { // 审核状态不是“待审核”，就弹出提示
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            throw new Error()
          } else {
            this.doSubmit('agree', callback)
          }
        })
      },
      // 表单提交
      // 表单提交
      doSubmit (status, callback) {
        if (status === 'save') {
          // 暂存
          // this.inputForm.status = '1'
          this.loading = true
          this.reportCancellApplyService.saveForm(this.inputForm).then(({data}) => {
            // callback(data.businessTable, data.businessId, this.inputForm)
            this.close()
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
          return
        } else if (status === 'start') {
          // 送审  待审核
          this.inputForm.status = '2'
        } else if (status === 'agree') {
          // 审核同意
          this.inputForm.agreeDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
          this.inputForm.agreeUserId = this.$store.state.user.id
          this.inputForm.status = '5'
        }
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            if (this.commonJS.isEmpty(this.inputForm.createDate)) {
              this.inputForm.createDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
            }
            this.inputForm.cwProjectInfoList.forEach((item, index) => {
              if (this.commonJS.isEmpty(this.inputForm.cwProjectInfoList[index].reportDate)) {
                this.$message.error('报告日期不能为空')
                this.loading = false
                throw new Error('报告日期不能为空')
              }
              if (this.commonJS.isEmpty(this.inputForm.cwProjectInfoList[index].reportType)) {
                this.$message.error('报告类型不能为空')
                this.loading = false
                throw new Error('报告类型不能为空')
              }
              if (this.commonJS.isEmpty(this.inputForm.cwProjectInfoList[index].opinionType)) {
                this.$message.error('意见类型不能为空')
                this.loading = false
                throw new Error('意见类型不能为空')
              }
            })
            projectReportService.saveForm(this.inputForm).then(({data}) => {
              callback(data.businessTable, data.businessId, this.inputForm)
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          }
        })
      },
      async updateStatusById (type) {
        if (type === 'reject' || type === 'reback') {
          await this.reportCancellApplyService.queryById(this.inputForm.id).then(({data}) => {
            if (data.status !== '2') { // status的值不等于“审核中”就弹出提示
              this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
              throw new Error()
            } else {
              if (type === 'reject') {
                // 驳回
                this.inputForm.status = '4'
                let param = {status: '4', id: this.inputForm.id}
                this.reportCancellApplyService.updateStatusById(param)
              }
              if (type === 'reback') {
                // 撤回
                let param = {status: '3', id: this.inputForm.id}
                this.reportCancellApplyService.updateStatusById(param)
              }
            }
          })
        }
      },
      close () {
        this.inputForm = {
          id: '',
          createDate: '',
          createBy: {
            id: '',
            name: ''
          },
          remarks: '',
          projectNumber: '',
          projectName: '',
          officeId: '',
          projectMoney: '',
          auditYear: '',
          planStartDate: '',
          planEndDate: '',
          projectMasterId: '',
          projectLeaderId: '',
          procInsId: '',
          processDefinitionId: '',
          status: '',
          workAttachmentDtoList: [],
          cwProjectClientInfoDTOList: [],
          contractName: '',
          contractAmount: '',
          contractNum: '',
          payerSubject: '',
          paymentMethod: '',
          contractId: '',
          projectMaster2Name: '',
          projectMasterName: ''
        }
        this.$refs.inputForm.resetFields()
        this.visible = false
      },
      tabHandleClick (event) {
        // console.log(event)
      },
      // 新增
      // eslint-disable-next-line no-dupe-keys
      // insertEvent (type) {
      //   if (type === 'client') {
      //     let d = {
      //       no: '',
      //       name: '',
      //       companyLevel: ''
      //     }
      //     if (this.commonJS.isEmpty(this.inputForm.cwProjectClientInfoDTOList)) {
      //       this.inputForm.cwProjectClientInfoDTOList = []
      //     }
      //     this.$refs.clientTable.insertAt(d)
      //     this.inputForm.cwProjectClientInfoDTOList.push(d)
      //     this.tableKeyClient = Math.random()
      //   }
      // },
      clearClientList () {
        // 项目直接对接联系人列表清除
        this.inputForm.clientList = []
        this.$forceUpdate()
      },
      // 删除
      removeEvent (row, rowIndex, type) {
        if (type === 'client') {
          this.$refs.clientTable.remove(row)
          // this.inputForm.cwProjectClientInfoDTOList.splice(rowIndex, 1)
          this.inputForm.cwProjectInfoList.splice(rowIndex, 1)
        }
      },
      getWorkClientChoose (list) {
        if (this.commonJS.isEmpty(this.inputForm.cwProjectInfoList)) {
          this.inputForm.cwProjectInfoList = []
        }
        let _this = this
        let _list = list
        const waitForEach = function () {
          return new Promise(function (resolve, reject) {
            _list.forEach((item) => {
              _this.inputForm.cwProjectInfoList.forEach(client => {
                if (item.id === client.servedUnitId) {
                  // _this.$message.error('已存在客户 “' + client.servedUnitName + '”，请重新选择')
                  // throw new Error('已存在客户 “' + client.servedUnitName + '”，请重新选择')
                }
              })
            })
            resolve()
          })
        }
        waitForEach().then(() => {
          list.forEach(item => {
            // eslint-disable-next-line no-unused-vars
            let d = {
              servedUnitName: item.name, // 被服务单位名称
              reportNumber: this.inputForm.projectNumber + '-0' + (this.inputForm.cwProjectInfoList.length + 1), // 报告流水号
              issueReport: '是',
              sealType: '未盖章',
              id: this.uuid,
              servedUnitId: item.id
            }
            // console.log('新增行数据填入')
            // console.log('item', item)
            // console.log('d', d)
            this.$refs.clientTable.insertAt(d)
            this.inputForm.cwProjectInfoList.push(d)
            // console.log('this.inputForm.cwProjectInfoList', this.inputForm.cwProjectInfoList)
            this.tableKeyClient = Math.random()
          })
        })
      },
      getContract (row) {
        // console.log('row', row)
        this.inputForm.projectName = row.projectName // 项目名称
        this.inputForm.projectId = row.id // 项目id
        this.inputForm.projectMasterName = row.projectMasterName // 项目经理1
        this.inputForm.projectMaster2Name = row.projectMaster2Name // 项目经理2
        this.inputForm.reportNo = row.reportNo // 报告文号
        this.inputForm.reportNewLineId = row.reportNewLineId // 新建行id
        this.clearClientList()
        this.$forceUpdate()
      },
    }
  }
</script>
<style scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
</style>
