<template>
<div>
  <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="formReadOnly"
           label-width="150px">
    <el-row  :gutter="0">
      <el-col :span="12">
        <el-form-item label="合同名称" prop="contractName">
          <el-input :disabled="true" v-model="inputForm.contractName"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item label="合同编号" prop="contractNo">
          <el-input :disabled="true" v-model="inputForm.contractNo"></el-input>
        </el-form-item>
      </el-col>

<!--      <el-col :span="12">-->
<!--        <el-form-item label="客户名称" prop="clientName">-->
<!--          <el-input :disabled="true" v-model="inputForm.clientName"></el-input>-->
<!--        </el-form-item>-->
<!--      </el-col>-->

      <el-col :span="12">
        <el-form-item label="借用人" prop="borrowName">
          <el-input :disabled="true" v-model="inputForm.borrowName"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item label="借用日期" prop="borrowData" :rules="[
                  {required: true, message:'请填写借用日期', trigger:'blur'}
               ]">
          <el-date-picker
            style="width: 100%"
            :disabled="this.inputForm.borrowType === '2'"
            v-model="inputForm.borrowData"
            value-format="YYYY-MM-DD"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item label="大概归还日期" prop="borrowRetData" :rules="[
                  {required: true, message:'请填写大概归还日期', trigger: 'blur'}
               ]">
          <el-date-picker
            style="width: 100%"
            :disabled="this.inputForm.borrowType === '2'"
            v-model="inputForm.borrowRetData"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>

    </el-row>

    <el-form-item label="备注" prop="remarks">
      <el-input v-model="inputForm.remarks"
                :disabled="this.inputForm.borrowType === '2'"
                type="textarea"
                :rows="5"
                maxlength="500"
                placeholder="请输入备注"
                show-word-limit>
      </el-input>
    </el-form-item>

  </el-form>
  <el-tabs v-model="activeName" type="border-card" @tab-click="tabHandleClick">
    <el-tab-pane label="合同正文" name="uploadFile">
      <!--        合同正文-->
      <UpLoadComponent ref="uploadFile"></UpLoadComponent>
    </el-tab-pane>
    <el-tab-pane label="参与签约方" name="contactParty">
      <el-row :gutter="15">
        <el-button type="primary" :disabled="true" style="margin-bottom: 15px" @click="openWorkClient">
          新增参与签约方
        </el-button>
      </el-row>
      <el-row  :gutter="15">
        <el-form :disabled="formReadOnly" style="width: 100%;">
          <vxe-table
            border
            show-overflow
            show-footer
            :column-config="{resizable: true}"
            ref="contactTable"
            :key="tableKeyClient"
            class="vxe-table-element"
            :data="inputForm.cwWorkClientContactDTOList"
            style=""
            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" title="操作" width="100">
              <template v-slot="scope">
                <el-button :disabled="true" 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="archiveFile">
      <!--        合同归档文件-->
      <UpLoadComponent ref="archiveFile"></UpLoadComponent>
    </el-tab-pane>

  </el-tabs>
  <WorkClientChooseForm ref="workClientChooseForm" @getWorkClientChoose="getWorkClientChoose"></WorkClientChooseForm>
</div>
</template>

<script>
	import userService from "@/api/sys/userService";
  import UpLoadComponent from '@/views/common/UpLoadComponent'
  // import WorkContractService from '@/api/sys/WorkContractService'
  import contractInfoService from '@/api/cw/workContract/ContractInfoService'
  // import WorkContractBorrowService from '@/api/sys/WorkContractBorrowService'
  import CwWorkContractBorrowService from '@/api/cw/workContract/CwWorkContractBorrowService'
  import WorkClientChooseForm from '../workClientInfo/WorkClientChooseForm'
  export default {
    data () {
      return {
        title: '',
        method: '',
        visible: false,
        loading: false,
        inputForm: {
          cwWorkClientContactDTOList: [],
          id: '',
          contractName: '',
          contractNo: '',
          borrowName: '',
          borrowData: '',
          borrowRetData: '',
          remarks: '',
          borrowType: '',
          type: ''
        },
        tableKeyClient: '1',
        activeName: 'uploadFile'
      }
    },
    props: {
      businessId: {
        type: String,
        default: ''
      },
      formReadOnly: {
        type: Boolean,
        default: false
      }
    },
    components: {
      UpLoadComponent,
      WorkClientChooseForm
    },
    // workContractBorrowService: null,
    cwWorkContractBorrowService: null,
    // workContractService: null,
    created () {
      // this.workContractBorrowService = new WorkContractBorrowService()
      this.cwWorkContractBorrowService = new CwWorkContractBorrowService()
      // this.workContractService = new WorkContractService()
    },
    watch: {
      'businessId': {
        handler (newVal) {
          if (this.businessId) {
            this.init(this.businessId)
          } else {
            this.$nextTick(() => {
              this.$refs.inputForm.resetFields()
            })
          }
        },
        immediate: true,
        deep: false
      }
    },
    computed: {
      userName () {
        return this.$store.state.user.name
      }
    },
    methods: {
      init (id) {
        if (id) {
          this.loading = true
          this.inputForm.id = id
          this.$nextTick(() => {
            this.$refs.inputForm.resetFields()
            this.cwWorkContractBorrowService.findById(this.inputForm.id).then((data) => {
              this.$refs.archiveFile.clearUpload()
              this.$refs.uploadFile.clearUpload()
              if (this.commonJS.isEmpty(data.id)) {
                contractInfoService.findById(this.inputForm.id).then((data) => {
                  this.inputForm = this.recover(this.inputForm, data)
                  // this.inputForm.borrowName = this.userName
					if (this.commonJS.isEmpty(this.inputForm.borrowName)){
						this.inputForm.borrowName = this.userName
					}
                  this.inputForm.borrowData = this.moment(new Date()).format('YYYY-MM-DD')
                  this.$refs.uploadFile.newUpload('view', data.contractProperList, 'cwWorkContract', null, null, null, null, false)
                  this.$refs.archiveFile.newUpload('view', data.contractInfoList, 'cwWorkContract', null, null, null, null, false)
                  // console.log('data', data)
                  this.loading = false
                })
              } else {
                console.log('data2', data)
                contractInfoService.findFileInfoById(data.contractInfoId).then((data) => {
                  this.inputForm.cwWorkClientContactDTOList = data.cwWorkClientContactDTOList
                  this.$refs.uploadFile.newUpload('view', data.contractProperList, 'cwWorkContract', null, null, null, null, false)
                  this.$refs.archiveFile.newUpload('view', data.contractInfoList, 'cwWorkContract', null, null, null, null, false)
                })
                this.inputForm = this.recover(this.inputForm, data)
                // this.inputForm.borrowName = this.userName
				  if (this.commonJS.isEmpty(this.inputForm.borrowName)){
					  this.inputForm.borrowName = this.userName
				  }
                // this.inputForm.borrowData = new Date()
				  this.inputForm.borrowData = this.moment(new Date()).format('YYYY-MM-DD')
                this.loading = false
              }
            })
          })
        }
      },
      tabHandleClick (event) {
        // console.log(event)
      },
      openWorkClient () {
        this.$refs.workClientChooseForm.init()
      },
      removeEvent (row, rowIndex, type) {
        if (type === 'client') {
          this.$refs.contactTable.remove(row)
          this.inputForm.cwWorkClientContactDTOList.splice(rowIndex, 1)
        }
      },
      getWorkClientChoose (list) {
        // console.log('list', list)
        if (this.commonJS.isEmpty(this.inputForm.cwWorkClientContactDTOList)) {
          this.inputForm.cwWorkClientContactDTOList = []
        }
        let _this = this
        let _list = list
        const waitForEach = function () {
          return new Promise(function (resolve, reject) {
            _list.forEach((item) => {
              _this.inputForm.cwWorkClientContactDTOList.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.contactTable.insertAt(item)
            this.inputForm.cwWorkClientContactDTOList.push(item)
            this.tableKeyClient = Math.random()
          })
        })
      },
      // 表单提交
      startForm (callback) {
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            let id = this.inputForm.id
            this.loading = true
            this.inputForm.contractInfoId = id
            var date1 = new Date(this.inputForm.borrowData)
            var date2 = new Date(this.inputForm.borrowRetData)
            if ((date2 - date1) < 0) {
            // if (!new Date(this.inputForm.borrowData) < new Date(this.inputForm.borrowRetData)) {
              this.loading = false
              this.$message.error('大概归还日期要比借用日期晚')
              throw new Error('大概归还日期要比借用日期晚')
            } else {
              this.inputForm.borrowType = '2'
              this.cwWorkContractBorrowService.save(this.inputForm).then((data) => {
				  //去后台查询该员工所属部门的部门主任
				  userService.getDepartmentId().then((assignee) =>{
					  this.inputForm.assignee = assignee.id
					  callback(data.businessTable, data.businessId, this.inputForm)
					  this.$refs.inputForm.resetFields()
					  this.loading = false
				  })
              }).catch(() => {
                this.$refs.inputForm.resetFields()
                this.loading = false
              })
            }

            // this.workContractBorrowService.save(this.inputForm).then((data) => {
            //   callback(data.businessTable, data.businessId, this.inputForm)
            //   this.$refs.inputForm.resetFields()
            //   this.loading = false
            // }).catch(() => {
            //   this.$refs.inputForm.resetFields()
            //   this.loading = false
            // })
          }
        })
      },
      // 同意
      agreeForm (callback) {
        this.inputForm.borrowType = '5'
        this.cwWorkContractBorrowService.updateMessageStatusById(this.inputForm).then((data) => {
          this.cwWorkContractBorrowService.updateStatusById(this.inputForm)
          callback(data.businessTable, data.businessId, this.inputForm)
          this.$refs.inputForm.resetFields()
          this.loading = false
        }).catch(() => {
          this.$refs.inputForm.resetFields()
          this.loading = false
        })
        // this.workContractBorrowService.updateMessageStatusById(this.inputForm).then((data) => {
        //   callback(data.businessTable, data.businessId, this.inputForm)
        //   this.$refs.inputForm.resetFields()
        //   this.loading = false
        // }).catch(() => {
        //   this.$refs.inputForm.resetFields()
        //   this.loading = false
        // })
      },
      // 关闭
      close () {
        this.$refs.inputForm.resetFields()
        this.visible = false
        // this.businessId = ''
      },
      // 更改状态
      updateStatusById (type) {
        // console.log('updateStatusById', this.inputForm)
        if (type === 'agree') {
          this.inputForm.borrowType = '5'
          this.cwWorkContractBorrowService.updateStatusById(this.inputForm)
          // this.workContractBorrowService.updateStatusById(this.inputForm)
        }
        if (type === 'reject') {
          this.inputForm.borrowType = '0'
          this.cwWorkContractBorrowService.updateStatusById(this.inputForm).then(() => {
            this.inputForm.borrowType = '3'
            this.inputForm.type = 'reject'
            this.cwWorkContractBorrowService.updateMessageStatusById(this.inputForm)
          })
        }
        if (type === 'reback') {
          this.inputForm.borrowType = '0'
          this.cwWorkContractBorrowService.updateStatusById(this.inputForm)
          // this.workContractBorrowService.updateStatusById(this.inputForm)
        }
      }
    }
  }
</script>


