<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-divider content-position="left"><i class="el-icon-document"></i> 选择合同</el-divider>
          <el-row  :gutter="15">
            <el-col :span="24">
              <el-form-item label="合同名称" prop="contractName"
                            :rules="[
                          {required: true, message:'合同不能为空', trigger:'blur'},
                          {required: true, message:'合同不能为空', trigger:'change'}
                 ]">
                <el-input size="medium" :readonly="true" @focus="openContract()" v-model="inputForm.contractName" placeholder="请选择合同">
                  <el-button slot="append" icon="el-icon-search" @click="openContract()"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同金额(元)" prop="contractAmount"
                            :rules="[
                 ]">
                <el-input :disabled="true" v-model="inputForm.contractAmount" placeholder="请填写合同金额"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同份数" prop="contractNum"
                            :rules="[
                 ]">
                <el-input :disabled="true" v-model="inputForm.contractNum" placeholder="请填写合同份数"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="付款主体" prop="payerSubject"
                            :rules="[
                 ]">
                <el-select :disabled="true" v-model="inputForm.payerSubject" placeholder="请选择付款主体" style="width:100%;">
                  <el-option
                    v-for="item in $dictUtils.getDictList('cw_payment_subject')"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="付款方式" prop="paymentMethod"
                            :rules="[
                 ]">
                <el-select :disabled="true" v-model="inputForm.paymentMethod" placeholder="请选择付款方式" style="width:100%;">
                  <el-option
                    v-for="item in $dictUtils.getDictList('cw_payment_method')"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider content-position="left"><i class="el-icon-document"></i> 项目信息</el-divider>
              <el-row  :gutter="15">
                <el-col :span="12">
                  <el-form-item label="项目名称" prop="projectName"
                                :rules="[
                                {required: true, message:'项目名称不能为空', trigger:'blur'}
                   ]">
                    <el-input v-model="inputForm.projectName" placeholder="请填写项目名称" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目编号" prop="projectNumber"
                                :rules="[
                   ]">
                    <el-input :disabled="true" v-model="inputForm.projectNumber" placeholder="请填写项目编号" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目所属部门" prop="officeId"
                                :rules="[
                                {required: true, message:'项目所属部门不能为空', trigger:'blur'}
                   ]">
                    <SelectTree
                      ref="officeTree"
                      :props="{
                          value: 'id',             // ID字段名
                          label: 'name',         // 显示名称
                          children: 'children'    // 子级字段名
                        }"
                      :url="`/sys/office/treeData?type=2`"
                      :value="inputForm.officeId"
                      :accordion="true"
                      size="large"
                      @getValue="(value) => {inputForm.officeId=value}"/>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目金额" prop="projectMoney"
                                :rules="[
                   ]">
                    <el-input-number
                      v-model="inputForm.projectMoney"
                      controls-position="right"
                      style="width:100%"
                      :precision="2"
                      :max="9999999999"
                      :step="0.01"
                      :min="0"
                      placeholder="请填写项目金额"
                      :controls="false"
                      clearable>
                    </el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="审计期间" prop="auditYear"
                                :rules="[
                   ]">
                    <el-date-picker
                      v-model="inputForm.auditYear"
                      type="year"
                      value-format="yyyy"
                      placeholder="选择评审计期间"
                      style="width:100%"
                      placement="bottom-start"
                      clearable>
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目预计开始时间" prop="planStartDate"
                                :rules="[
                                {required: true, message:'项目预计开始时间不能为空', trigger:'blur'}
                   ]">
                    <el-date-picker
                      v-model="inputForm.planStartDate"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="选择项目预计开始时间"
                      style="width:100%"
                      placement="bottom-start"
                      clearable>
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目预计结束时间" prop="planEndDate"
                                :rules="[
                                {required: true, message:'项目预计结束时间不能为空', trigger:'blur'}
                   ]">
                    <el-date-picker
                      v-model="inputForm.planEndDate"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="选择项目预计结束时间"
                      style="width:100%"
                      placement="bottom-start"
                      clearable>
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目经理" prop="projectMasterId"
                                :rules="[
                                {required: true, message:'项目经理不能为空', trigger:'blur'}
                   ]">
<!--                    <el-input v-model="inputForm.projectMasterId" placeholder="请填写项目经理" clearable></el-input>-->
                    <UserSelect size="medium" :disabled="formReadOnly" :limit='1' :value="inputForm.projectMasterId" @getValue='(value) => {inputForm.projectMasterId = value}'></UserSelect>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="现场负责人" prop="projectLeaderId"
                                :rules="[
                   ]">
                    <UserSelect size="medium" :disabled="formReadOnly" :limit='1' :value="inputForm.projectLeaderId" @getValue='(value) => {inputForm.projectLeaderId = value}'></UserSelect>
                  </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-row>
            </el-form>
        <el-tabs v-model="activeName" type="border-card" @tab-click="tabHandleClick">
          <el-tab-pane label="被服务单位" name="client">
            <el-row :gutter="15">
              <el-button type="info" style="margin-bottom: 15px" size="mini" :disabled="formReadOnly" @click="openWorkClient">
                新增被服务单位
              </el-button>
            </el-row>
            <el-row  :gutter="15">
              <el-form :disabled="formReadOnly">
                <vxe-table
                  border
                  show-overflow
                  show-footer
                  :column-config="{resizable: true}"
                  ref="clientTable"
                  :key="tableKeyClient"
                  class="vxe-table-element"
                  :data="inputForm.cwProjectClientInfoDTOList"
                  style=""
                  @cell-click=""
                  @edit-closed=""
                  highlight-current-row
                  :edit-config="{trigger: 'click', mode: 'row', showStatus: false, autoClear: false}"
                >
                  <vxe-table-column align="center" field="no" title="客户编号" :edit-render="{}">
                    <template v-slot:edit="scope">
                      <el-input :readonly="true" v-model="scope.row.no" placeholder="客户编号" clearable></el-input>
                    </template>
                  </vxe-table-column>
                  <vxe-table-column align="center" field="name" title="客户名称" :edit-render="{}">
                    <template v-slot:edit="scope">
                      <el-input :readonly="true" v-model="scope.row.name" placeholder="客户名称" clearable></el-input>
                    </template>
                  </vxe-table-column>
                  <vxe-table-column align="center" field="companyLevel" title="层级" :edit-render="{}">
                    <template v-slot:edit="scope">
                      <el-input :readonly="true" v-model="scope.row.companyLevel" placeholder="层级" clearable></el-input>
                    </template>
                  </vxe-table-column>
                  <vxe-table-column align="center" title="操作" width="100">
                    <template v-slot="scope">
                      <el-button size="mini" type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'client')">删除</el-button>
                    </template>
                  </vxe-table-column>
                </vxe-table>
              </el-form>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="附件" name="files">
            <!--        附件-->
            <UpLoadComponent ref="uploadComponent"></UpLoadComponent>
          </el-tab-pane>

        </el-tabs>
      </el-col>
    </el-row>
    <WorkContractChooseCom ref="workContractChooseCom" @getContract="getContract"></WorkContractChooseCom>
    <WorkClientChooseForm ref="workClientChooseForm" @getWorkClientChoose="getWorkClientChoose"></WorkClientChooseForm>
  </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 '@/components/userSelect'
  import ProjectRecordsService from '@/api/cw/projectRecords/ProjectRecordsService'
  import EnterpriseSearchService from '@/api/cw/common/EnterpriseSearchService'
  import WorkClientChooseForm from '../workClientInfo/WorkClientChooseForm'
  import WorkContractChooseCom from './WorkContractChooseCom'
  export default {
    props: {
      businessId: {
        type: String,
        default: ''
      },
      formReadOnly: {
        type: Boolean,
        default: false
      },
      status: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        title: '',
        method: '',
        loading: false,
        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: ''
        },
        keyWatch: '',
        activeName: 'client',
        tableKey: '',
        tableKeyClient: '1'
      }
    },
    projectRecordsService: null,
    enterpriseSearchService: null,
    created () {
      this.enterpriseSearchService = new EnterpriseSearchService()
      this.projectRecordsService = new ProjectRecordsService()
    },
    computed: {
      bus: {
        get () {
          this.$refs.uploadComponent.setDividerName('附件', false)
          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: {
      SelectUserTree,
      UpLoadComponent,
      SelectTree,
      UserSelect,
      WorkClientChooseForm,
      WorkContractChooseCom
    },
    methods: {
      getKeyWatch (keyWatch) {
        this.keyWatch = keyWatch
      },
      init (method, id) {
        this.activeName = 'client'
        this.projectRecordsService = new ProjectRecordsService()
        this.method = method
        this.inputForm = {
          id: '',
          createDate: '',
          createBy: {
            id: '',
            name: JSON.parse(localStorage.getItem('user')).name
          },
          remarks: '',
          projectNumber: '',
          projectName: '',
          officeId: '',
          projectMoney: '',
          auditYear: '',
          planStartDate: '',
          planEndDate: '',
          projectMasterId: '',
          projectLeaderId: '',
          procInsId: '',
          processDefinitionId: '',
          status: '',
          workAttachmentDtoList: [],
          cwProjectClientInfoDTOList: [],
          contractName: '',
          contractAmount: '',
          contractNum: '',
          payerSubject: '',
          paymentMethod: '',
          contractId: ''
        }
        this.inputForm.id = id
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          this.loading = true
          this.projectRecordsService.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.workAttachmentDtoList)) {
              this.inputForm.workAttachmentDtoList = []
            }
            if (this.commonJS.isEmpty(this.inputForm.createDate)) {
              this.inputForm.createDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
            }
            if (this.commonJS.isEmpty(this.inputForm.createBy.name)) {
              this.inputForm.createBy.name = JSON.parse(localStorage.getItem('user')).name
            }
            if (this.commonJS.isEmpty(this.inputForm.officeId)) {
              this.inputForm.officeId = JSON.parse(localStorage.getItem('user')).officeDTO.id
            }
            if (this.formReadOnly) {
              this.method = 'view'
            }
            this.$refs.uploadComponent.newUpload(this.method, this.inputForm.workAttachmentDtoList, 'cw_project_records', null, null, null, null, false)
            if (this.commonJS.isEmpty(this.inputForm.cwProjectClientInfoDTOList)) {
              this.inputForm.cwProjectClientInfoDTOList = []
            }
            if (this.commonJS.isEmpty(this.inputForm.projectMasterId)) {
              this.inputForm.projectMasterId = JSON.parse(localStorage.getItem('user')).id
            }
            if (this.commonJS.isEmpty(this.inputForm.projectLeaderId)) {
              this.inputForm.projectLeaderId = JSON.parse(localStorage.getItem('user')).id
            }
            if (this.commonJS.isEmpty(this.inputForm.projectMoney)) {
              this.inputForm.projectMoney = 0
            }
            this.loading = false
          })
        })
      },
      saveForm (callback) {
        this.doSubmit('save', callback)
      },
      startForm (callback) {
        this.doSubmit('start', callback)
      },
      async agreeForm (callback) {
        await this.projectRecordsService.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
          if (this.$refs.uploadComponent.checkProgress()) {
            this.loading = false
            return
          }
          this.inputForm.workAttachmentDtoList = this.$refs.uploadComponent.getDataList()
          this.inputForm.createDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
          this.projectRecordsService.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'
        }
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            if (this.$refs.uploadComponent.checkProgress()) {
              this.loading = false
              return
            }
            this.inputForm.workAttachmentDtoList = this.$refs.uploadComponent.getDataList()
            if (this.commonJS.isEmpty(this.inputForm.createDate)) {
              this.inputForm.createDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
            }
            this.projectRecordsService.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') {
          if (await this.$refs.uploadComponent.checkProgress()) {
            this.loading = false
            throw new Error()
          }
          await this.projectRecordsService.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.projectRecordsService.updateStatusById(param)
              }
              if (type === 'reback') {
                // 撤回
                let param = {status: '3', id: this.inputForm.id}
                this.projectRecordsService.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: ''
        }
        this.$refs.uploadComponent.clearUpload()
        this.$refs.inputForm.resetFields()
      },
      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()
        }
      },
      // 删除
      removeEvent (row, rowIndex, type) {
        if (type === 'client') {
          this.$refs.clientTable.remove(row)
          this.inputForm.cwProjectClientInfoDTOList.splice(rowIndex, 1)
        }
      },
      openWorkClient () {
        this.$refs.workClientChooseForm.init()
      },
      getWorkClientChoose (list) {
        if (this.commonJS.isEmpty(this.inputForm.cwProjectClientInfoDTOList)) {
          this.inputForm.cwProjectClientInfoDTOList = []
        }
        let _this = this
        let _list = list
        const waitForEach = function () {
          return new Promise(function (resolve, reject) {
            _list.forEach((item) => {
              _this.inputForm.cwProjectClientInfoDTOList.forEach(client => {
                if (item.no === client.no) {
                  _this.$message.error('已存在客户 “' + client.name + '”，请重新选择')
                  throw new Error('已存在客户 “' + client.name + '”，请重新选择')
                }
              })
            })
            resolve()
          })
        }
        waitForEach().then(() => {
          list.forEach(item => {
            this.$refs.clientTable.insertAt(item)
            this.inputForm.cwProjectClientInfoDTOList.push(item)
            this.tableKeyClient = Math.random()
          })
        })
      },
      getContract (row) {
        this.inputForm.contractName = row.contractName
        this.inputForm.contractAmount = row.contractAmount
        this.inputForm.contractNum = row.contractNum
        this.inputForm.payerSubject = row.payerSubject
        this.inputForm.paymentMethod = row.paymentMethod
        this.inputForm.contractId = row.id
      },
      openContract () {
        this.$refs.workContractChooseCom.init()
      }
    }
  }
</script>
<style scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
</style>
