<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <el-row>
      <el-col :span="24">

        <el-form size="middle" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="formReadOnly"
                 label-width="135px" @submit.native.prevent>
          <el-row  :gutter="15">
            <el-col :span="12">
              <el-form-item label="报告文号" prop="reportNo"
                            :rules="[
                              {required: true, message:'报告文号不能为空', trigger:'blur'},
                              {required: true, message:'报告文号不能为空', trigger:'change'}
                   ]">
                <el-input size="medium" :readonly="true" @focus="openContractForm()" v-model="inputForm.reportNo" placeholder="请填写报告文号">
                  <el-button slot="append" icon="el-icon-search" @click="openContractForm()"></el-button>
                </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="[
                              {required: true, message:'作废原因不能为空', trigger:'blur'}
                   ]">
                <el-input type="textarea" v-model="inputForm.cancellateReason" placeholder="请填写作废原因" clearable></el-input>
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>
      </el-col>
    </el-row>
    <ReportCancellApplyChooseCom  ref="reportCancellApplyChooseCom" @getProject="getContract"></ReportCancellApplyChooseCom>
  </div>
</template>

<script>
  import UpLoadComponent from '@/views/common/UpLoadComponent'
  import SelectUserTree from '@/views/modules/utils/treeUserSelect'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import UserSelect from '../workClientInfo/clientUserSelect'
  import ProjectRecordsService from '@/api/cw/projectRecords/ProjectRecordsService'
  // import ProjectReportService from '@/api/cw/reportManagement/ProjectReportService'
  import ReportCancellApplyService from '@/api/cw/reportCancellApply/ReportCancellApplyService'
  import EnterpriseSearchService from '@/api/cw/common/EnterpriseSearchService'
  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: JSON.parse(localStorage.getItem('user')).name
          },
          remarks: '',
          reportNo: '',
          projectName: '',
          cancellateReason: '',
          reportSponsor: '',
          projectMasterName: '',
          projectMaster2Name: '',
          cwFileInfoList: [],
          servedUnitId: '',
          status: ''
        },
        keyWatch: '',
        activeName: 'newRow',
        tableKey: '',
        tableKeyClient: '1'
      }
    },
    projectRecordsService: null,
    // ProjectReportService: null,
    ReportCancellApplyService: null,
    enterpriseSearchService: null,
    created () {
      this.enterpriseSearchService = new EnterpriseSearchService()
      this.projectRecordsService = new ProjectRecordsService()
      // this.projectReportService = new ProjectReportService()
      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()
            })
          }
        }
      },
      'loading': {
        handler (newVal) {
          this.$emit('changeLoading', newVal)
        }
      }
    },
    components: {
      SelectUserTree,
      UpLoadComponent,
      SelectTree,
      UserSelect,
      ReportCancellApplyChooseCom
    },
    methods: {
      getKeyWatch (keyWatch) {
        this.keyWatch = keyWatch
      },
      init (method, id) {
        this.activeName = 'newRow'
        this.projectRecordsService = new ProjectRecordsService()
        // this.projectReportService = new ProjectReportService()
        this.reportCancellApplyService = new ReportCancellApplyService()
        this.method = method
        this.inputForm = {
          projectId: '',
          reportNewLineId: '',
          id: '',
          createDate: '',
          createBy: {
            id: '',
            name: JSON.parse(localStorage.getItem('user')).name
          },
          remarks: '',
          reportNo: '',
          projectName: '',
          cancellateReason: '',
          reportSponsor: '',
          projectMasterName: '',
          projectMaster2Name: ''
        }
        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.$refs.uploadComponent.clearUpload()
            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
          })
          // this.projectReportService.queryById(this.inputForm.id).then(({data}) => {
          //   // this.$refs.uploadComponent.clearUpload()
          //   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
          // })
        })
      },
      openContractForm () {
        if (!this.commonJS.isEmpty(this.inputForm.contractId)) {
          this.$refs.reportCancellApplyChooseCom.init()
        } else {
          this.$refs.reportCancellApplyChooseCom.init()
        }
      },
      getContract (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.inputForm.reportSponsor = row.reportSponsor // 报告主办人
        this.clearClientList()
        this.$forceUpdate()
      },
      clearClientList () {
        // 项目直接对接联系人列表清除
        this.inputForm.clientList = []
        this.$forceUpdate()
      },
      saveForm (callback) {
        this.doSubmit('save', callback)
      },
      startForm (callback) {
        this.loading = true
        if (this.commonJS.isNotEmpty(this.inputForm.id)) {
          this.reportCancellApplyService.queryById(this.inputForm.id).then(({data}) => {
            if (data.status !== '0' && data.status !== '1' && data.status !== '3') { // 审核状态不是“未发起”或“暂存”或“撤回”，就弹出提示
              this.loading = false
              this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
              throw new Error()
            } else {
              this.doSubmit('start', callback)
            }
          })
        } else {
          this.doSubmit('start', callback)
        }
      },
      async agreeForm (callback) {
        this.loading = true
        await this.reportCancellApplyService.queryById(this.inputForm.id).then(({data}) => {
          if (data.status !== '2') { // 审核状态不是“待审核”，就弹出提示
            this.loading = false
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            throw new Error()
          } else {
            this.doSubmit('agree', callback)
          }
        })
        // await this.projectReportService.queryById(this.inputForm.id).then(({data}) => {
        //   console.log('进来了看看data', data)
        //   if (data.status !== '2') { // 审核状态不是“待审核”，就弹出提示
        //     this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
        //     throw new Error()
        //   } else {
        //     this.doSubmit('agree', callback)
        //   }
        // })
      },
      reapplyForm (callback) {
        this.loading = true
        this.reportCancellApplyService.queryById(this.inputForm.id).then(({data}) => {
          if (data.status !== '4') { // 审核状态不是“驳回”，就弹出提示
            this.loading = false
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
          } else {
            this.doSubmit('reapply', callback)
          }
        })
      },
      // 表单提交
      doSubmit (status, callback) {
        if (status === 'save') {
          // 暂存
          this.inputForm.status = '1'
          this.loading = true
          this.inputForm.createDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
          // 验证报告 日期报告 类型是否出具报告 意见类型 是否为空
          // eslint-disable-next-line no-unused-expressions
          this.reportCancellApplyService.saveForm(this.inputForm).then(({data}) => {
            callback(data.businessTable, data.businessId, this.inputForm)
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
          // this.projectReportService.saveForm(this.inputForm).then(({data}) => {
          //   callback(data.businessTable, data.businessId, this.inputForm)
          //   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'
        } else if (status === 'reapply') {
          this.inputForm.status = '2'
        }
        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.reportCancellApplyService.saveForm(this.inputForm).then(({data}) => {
              if (status === 'start' || status === 'reapply') {
                this.inputForm.title = `${this.$store.state.user.name} 发起了 [${this.inputForm.reportNo}] - ${this.inputForm.projectName} [财务-报告作废]`
              }
              this.inputForm.id = data.businessId
              callback(data.businessTable, data.businessId, this.inputForm)
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
            // this.projectReportService.saveForm(this.inputForm).then(({data}) => {
            //   console.log('businessTable', data.businessTable)
            //   console.log('businessId', data.businessId)
            //   callback(data.businessTable, data.businessId, this.inputForm)
            //   this.loading = false
            // }).catch(() => {
            //   this.loading = false
            // })
          } else {
            this.loading = false
          }
        })
      },
      async updateStatusById (type, callback) {
        this.loading = true
        if (type === 'reject' || type === 'reback') {
          await this.reportCancellApplyService.queryById(this.inputForm.id).then(({data}) => {
            if (data.status !== '2') { // status的值不等于“审核中”就弹出提示
              this.loading = false
              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).then(() => {
                  this.loading = false
                  callback()
                })
                // this.projectRecordsService.updateStatusById(param)
              }
              if (type === 'reback') {
                // 撤回
                let param = {status: '3', id: this.inputForm.id}
                // this.projectRecordsService.updateStatusById(param)
                this.reportCancellApplyService.updateStatusById(param).then(() => {
                  this.loading = false
                  callback()
                })
              }
            }
          })
          // await this.projectReportService.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.projectReportService.updateStatusById(param)
          //       // this.projectRecordsService.updateStatusById(param)
          //     }
          //     if (type === 'reback') {
          //       // 撤回
          //       let param = {status: '3', id: this.inputForm.id}
          //       // this.projectRecordsService.updateStatusById(param)
          //       this.projectReportService.updateStatusById(param)
          //     }
          //   }
          // })
        } else if (type === 'hold') {
          this.reportCancellApplyService.queryById(this.inputForm.id).then(({data}) => {
            if (data.status !== '4') { // status的值不等于“驳回”就弹出提示
              this.loading = false
              this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
              throw new Error()
            } else {
              // 终止
              let param = {status: '1', id: this.inputForm.id}
              this.reportCancellApplyService.updateStatusById(param).then(() => {
                this.loading = false
                callback()
              })
            }
          })
        }
      },
      close () {
        this.inputForm = {
          id: '',
          createDate: '',
          createBy: {
            id: '',
            name: JSON.parse(localStorage.getItem('user')).name
          },
          remarks: '',
          reportNo: '',
          projectName: '',
          cancellateReason: '',
          reportSponsor: '',
          projectMasterName: '',
          projectMaster2Name: ''
        }
        // this.$refs.uploadComponent.clearUpload()
        this.$refs.inputForm.resetFields()
      },
      tabHandleClick (event) {
        // console.log(event)
      },
      // 删除
      removeEvent (row, rowIndex, type) {
        if (type === 'client') {
          this.$refs.clientTable.remove(row)
        }
      }
    }
  }
</script>
<style scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
</style>
