<template>
  <div>
    <el-form size="middle" :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="contractNo">
            <el-input maxlength="64" :disabled="true" v-model="inputForm.contractNo" placeholder="自动生成"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同名称" prop="contractName"
                        :rules="[{required: true, message: '合同名称不能为空', trigger: 'blur'}
                 ]">
            <el-input v-model="inputForm.contractName" placeholder="请输入合同名称"     clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同状态" prop="contractStatus">
            <el-input maxlength="64" v-model="inputForm.contractStatus" :disabled="true" placeholder="请输入合同状态"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="付款主体" prop="payerSubject"
                        :rules="[{required: true, message: '付款主体不能为空', trigger: 'blur'}
                 ]">
            <el-select 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="[{required: true, message: '付款方式不能为空', trigger: 'blur'}
                 ]">
            <el-select 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-col :span="12">
          <el-form-item label="签约日期" prop="signingDate"
                        :rules="[
                {required: true, message:'请输入签约日期', trigger:'blur'}
               ]">
            <el-date-picker
              placement="bottom-start"
              value-format="yyyy-MM-dd"
              v-model="inputForm.signingDate"
              style="width: 100%"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="合同金额(元)" prop="contractAmount"
                        :rules="[
                  {required: true, message:'请输入合同金额(元)', trigger:'blur'}
               ]">
            <el-input maxlength="15" v-model="inputForm.contractAmount" placeholder="请输入合同金额(元)"
                      @keyup.native="inputForm.contractAmount = twoDecimalPlaces(inputForm.contractAmount)"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="合同实际金额" prop="actualContractAmount">
            <el-input maxlength="64" :disabled="true" v-model="inputForm.actualContractAmount" ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="合同份数" prop="contractNum"
                        :rules="[{required: true, message: '合同份数', trigger: 'blur'}
                 ]">
            <el-input maxlength="64" v-model="inputForm.contractNum" placeholder="请输入合同份数"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="付款约定" prop="paymentAgreement">
            <el-input maxlength="64" v-model="inputForm.paymentAgreement" placeholder="请输入付款约定"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="修改次数" prop="changeNum"
                        :rules="[{required: true, message: '修改次数', trigger: 'blur'}
                 ]">
            <el-input maxlength="64" :disabled="true" v-model="inputForm.changeNum" placeholder="请输入修改次数"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item  prop="department" label="所属部门">
            <SelectTree
              ref="officeTree"
              :props="{
                  value: 'id',             // ID字段名
                  label: 'name',         // 显示名称
                  children: 'children'    // 子级字段名
                }"

              :url="`/sys/office/treeData?type=2`"
              :value="inputForm.department"
              :accordion="true"
              @getValue="(value) => {inputForm.department=value}"/>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="委托方联系人" prop="clientContacts"
                        :rules="[{required: true, message: '委托方联系人', trigger: 'blur'}
                 ]">
            <el-input maxlength="100" v-model="inputForm.clientContacts" placeholder="请输入委托方联系人"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="委托方联系人电话" prop="clientContactsPhone"
                        :rules="[{required: true, message: '委托方联系人电话', trigger: 'blur'}
                 ]">
            <el-input maxlength="15" v-model="inputForm.clientContactsPhone" placeholder="请输入委托方联系人电话"
                      @keyup.native="inputForm.clientContactsPhone = twoDecimalPlaces(inputForm.clientContactsPhone)"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="创建人" prop="createBy"
                        :rules="[{required: true, message: '创建人', trigger: 'blur'}
                 ]">
            <el-input maxlength="64" :disabled="true" v-model="inputForm.createBy" placeholder="请输入创建人"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="创建时间" prop="createDate">
            <el-date-picker
              placement="bottom-start"
              value-format="yyyy-MM-dd"
              v-model="inputForm.createDate"
              style="width: 100%"
              :disabled="true"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>

      </el-row>

      <el-tabs v-model="activeName" type="border-card" @tab-click="tabHandleClick">
        <el-tab-pane label="合同正文" name="contractProper">
          <!--        合同正文-->
          <UpLoadComponent ref="uploadComponent"></UpLoadComponent>
        </el-tab-pane>
        <el-tab-pane label="参与签约方" name="contactParty">
          <el-row :gutter="15">
            <el-button type="info" style="margin-bottom: 15px" size="mini" :disabled="method === 'view'" @click="openWorkClient">
              新增参与签约方
            </el-button>
          </el-row>
          <el-row  :gutter="15">
            <el-form :disabled="method === 'view'">
              <vxe-table
                border
                show-overflow
                show-footer
                :column-config="{resizable: true}"
                ref="contactTable"
                :key="tableKeyClient"
                class="vxe-table-element"
                :data="inputForm.cwWorkClientContactDTOList"
                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" 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="archiveFile">
          <!--        合同归档文件-->
          <UpLoadComponent ref="archiveFile"></UpLoadComponent>
        </el-tab-pane>

      </el-tabs>

      </el-form>
      <el-image-viewer
        v-if="showViewer"
        :on-close="closeViewer"
        :url-list="[url]"
        zIndex="9999"/>
    <WorkClientChooseForm ref="workClientChooseForm" @getWorkClientChoose="getWorkClientChoose"></WorkClientChooseForm>
  </div>
</template>

<script>
  // import WorkContractService from '@/api/sys/WorkContractService'
  import ContractInfoService from '@/api/cw/workContract/ContractInfoService'
  import UpLoadComponent from '@/views/common/UpLoadComponent'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import WorkClientSelect from '@/components/workClientInfoSelect'
  import WorkClientForm from '../workClientInfo/WorkClientForm'
  import WorkClientChooseForm from '../workClientInfo/WorkClientChooseForm'
  import OSSSerive, {
    httpRequest,
    toHref,
    openWindowOnUrl,
    handleRemove,
    fileName
  } from '@/api/sys/OSSService'
  import moment from 'moment'
  import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
  export default {
    data () {
      return {
        visable: false,
        gridData: [],
        radio: 0,
        tableData: [],
        dataList: [],
        dataListNew: [],
        title: '',
        method: '',
        isSubmit: false,
        visible: false,
        loading: false,
        returnForm: {
          clientId: '',
          name: '',
          contractDate: '',
          effectiveDate: '',
          closingDate: '',
          contractType: '',
          contractAmountType: '',
          contractAmount: '',
          contractOpposite: '',
          contractFees: [],
          fees: '',
          contractFee: '',
          describes: '',
          contractSpecial: '',
          remarks: '',
          clientName: '',
          contractProperList: [],
          status: '',
          customerNo: '',
          customerName: ''
        },
        inputForm: {
          contractNo: '',
          contractName: '',
          payerSubject: '',
          paymentMethod: '',
          signingDate: '',
          contractAmount: '',
          actualContractAmount: '',
          contractNum: '2',
          contractStatus: '新创建',
          paymentAgreement: '',
          changeNum: '0',
          department: '',
          clientContacts: '',
          clientContactsPhone: '',
          createBy: JSON.parse(localStorage.getItem('user')).name,
          createId: JSON.parse(localStorage.getItem('user')).id,
          createDate: '',
          contractProperList: [],
          cwWorkClientContactDTOList: []
        },
        activeName: 'contractProper',
        filesArra2: [],
        fileList: [],
        isFlag: true,
        showViewer: false, // 显示查看器
        url: '',
        rowurl: '',
        src: '',
        onedit: false,
        type: '',
        loadProgress: 0, // 动态显示进度条
        progressFlag: false, // 关闭进度条
        promi: null,
        tableKeyClient: '1',
        keyWatch: ''
      }
    },
    props: {
      businessId: {
        type: String,
        default: ''
      },
      formReadOnly: {
        type: Boolean,
        default: false
      }
    },
    components: {
      ElImageViewer,
      UpLoadComponent,
      SelectTree,
      WorkClientSelect,
      WorkClientForm,
      WorkClientChooseForm
    },
    // computed: {
    //   officeName () {
    //     return JSON.parse(localStorage.getItem('user')).officeDTO.name
    //   }
    // },
    ossService: null,
    contractInfoService: null,
    created () {
      this.ossService = new OSSSerive()
      this.contractInfoService = new ContractInfoService()
    },
    mounted () {
      window.onPreview = this.onPreview
    },
    computed: {
      officeName () {
        return JSON.parse(localStorage.getItem('user')).officeDTO.name
      },
      bus: {
        get () {
          this.$refs.archiveFile.setDividerName('附件', false)
          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()
            })
          }
        }
      }
    },
    methods: {
      getKeyWatch (keyWatch) {
        this.keyWatch = keyWatch
      },
      uploadVideoProcess (event, file, fileList) {
        this.progressFlag = true // 显示进度条
        this.loadProgress = parseInt(event.percent) // 动态获取文件上传进度
        if (this.loadProgress >= 100) {
          this.loadProgress = 100
          setTimeout(() => { this.progressFlag = false }, 1000) // 一秒后关闭进度条
        }
      },
      async toHref (row) {
        toHref(row)
      },
      onPreview (url) {
        this.url = url
        this.showViewer = true
      },
      // 关闭查看器
      closeViewer () {
        this.url = ''
        this.showViewer = false
      },
      init (method, id) {
        this.dataList = []
        this.dataListNew = []
        this.method = method
        this.inputForm = {
          contractNo: '',
          contractName: '',
          payerSubject: '',
          paymentMethod: '',
          signingDate: '',
          contractAmount: '',
          actualContractAmount: '',
          contractNum: '',
          contractStatus: '',
          paymentAgreement: '',
          changeNum: '',
          department: '',
          clientContacts: '',
          clientContactsPhone: '',
          createBy: JSON.parse(localStorage.getItem('user')).name,
          createId: JSON.parse(localStorage.getItem('user')).id,
          createDate: '',
          contractProperList: [],
          cwWorkClientContactDTOList: []
        }
        this.inputForm.id = id
        if (method === 'add') {
          // this.inputForm.contractAmountType = '1'
          this.title = `新建合同登记`
        } else if (method === 'edit') {
          this.title = '修改合同登记'
        } else if (method === 'view') {
          this.inputForm.showVi = false
          this.title = '查看合同登记'
        }
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          // if (method === 'edit' || method === 'view') { // 修改或者查看
          this.loading = true
          this.$refs.uploadComponent.clearUpload()
          this.contractInfoService.findById(this.inputForm.id).then(({data}) => {
            this.inputForm = this.recover(this.inputForm, data)
            // 对数值进行判断是否为空,为空则赋值默认值
            console.log('this.inputForm.contractStatus', this.inputForm.contractStatus)
            if (this.inputForm.contractStatus === undefined || this.inputForm.contractStatus === '') {
              this.inputForm.contractStatus = '新创建'
            }
            if (this.inputForm.contractNum === undefined || this.inputForm.contractNum === '') {
              this.inputForm.contractNum = '2'
            }
            if (this.inputForm.changeNum === undefined || this.inputForm.changeNum === '') {
              this.inputForm.changeNum = '0'
            }
            if (this.inputForm.createBy === undefined || this.inputForm.createBy === '') {
              this.inputForm.createBy = JSON.parse(localStorage.getItem('user')).name
            }
            if (this.inputForm.createId === undefined || this.inputForm.createId === '') {
              this.inputForm.createId = JSON.parse(localStorage.getItem('user')).id
            }
            const f = []
            if (data.fees !== null && data.fees !== undefined && data.fees !== '') {
              data.fees.split(',').forEach(item => {
                if (item !== null && item !== undefined && item !== '') {
                  f.push(item)
                }
              })
            }
            this.inputForm.contractFees = f
            if (this.formReadOnly) {
              method = 'view'
            }
            this.$refs.uploadComponent.newUpload(method, this.inputForm.contractProperList, 'cwWorkContract', null, null, null, null, false)
            this.$refs.archiveFile.newUpload('view', [], 'cwWorkContract', null, null, null, null, false)
            this.loading = false
          })
        })
      },
      // 查看
      view (id) {
        this.$refs.workClientForm.init('view', id)
      },
      // 新增
      // eslint-disable-next-line no-dupe-keys
      async insertEvent (type) {
        if (type === 'client') {
          let d = {
            no: '',
            name: ''
          }
          if (this.commonJS.isEmpty(this.inputForm.cwWorkClientContactDTOList)) {
            this.inputForm.cwWorkClientContactDTOList = []
          }
          this.$refs.contactTable.insertAt(d)
          this.inputForm.cwWorkClientContactDTOList.push(d)
          this.tableKeyClient = Math.random()
        }
        // if (type === 'client') {
        //   await this.$refs.contactTable.insert().then((data) => {
        //     console.log('data', data)
        //     if (this.commonJS.isEmpty(this.inputForm.cwWorkClientContactDTOList)) {
        //       this.inputForm.cwWorkClientContactDTOList = []
        //     }
        //     this.$nextTick(() => {
        //       this.inputForm.cwWorkClientContactDTOList.push(data)
        //     })
        //   })
        // }
      },

      // 删除
      removeEvent (row, rowIndex, type) {
        if (type === 'client') {
          this.$refs.contactTable.remove(row)
          this.inputForm.cwWorkClientContactDTOList.splice(rowIndex, 1)
        }
      },
      openWorkClient () {
        this.$refs.workClientChooseForm.init()
      },
      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()
          })
        })
      },
      // 表单提交
      // 暂存
      async saveForm (callback) {
        this.loading = true
        this.inputForm.status = '1'
        this.inputForm.contractProperList = this.$refs.uploadComponent.getDataList()
        console.log('this.inputForm', this.inputForm)
        await this.contractInfoService.save(this.inputForm).then(({data}) => {
          callback()
          this.$refs.inputForm.resetFields()
          this.loading = false
        }).catch(() => {
          this.$refs.inputForm.resetFields()
          this.loading = false
        })
      },
      // 送审
      startForm (callback) {
        this.$refs['inputForm'].validate(async (valid) => {
          if (valid) {
            this.loading = true
            this.inputForm.status = '2'
            this.inputForm.contractProperList = this.$refs.uploadComponent.getDataList()
            // this.inputForm.fees = this.inputForm.contractFees.join(',')
            await this.contractInfoService.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.$refs['inputForm'].validate(async (valid) => {
          if (valid) {
            this.loading = true
            this.inputForm.status = '2'
            this.inputForm.contractProperList = this.$refs.uploadComponent.getDataList()
            // this.inputForm.fees = this.inputForm.contractFees.join(',')
            await this.contractInfoService.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
            })
          }
        })
      },
      close () {
        this.$refs.inputForm.resetFields()
        this.inputForm.clientName = ''
        this.inputForm.cwWorkClientContactDTOList = []
        this.visible = false
        this.showVi = true
        this.$refs.uploadComponent.clearUpload()
      },
      tabHandleClick (event) {
        // console.log(event)
      },
      httpRequest (file) {
        httpRequest(file, fileName(file), 'workContract')
      },
      handleRemove () {
        this.fileList = handleRemove()
      },
      changes (file, fileList) {
        this.dataListNew = []
        this.dataList.forEach((item) => {
          this.dataListNew.push(item)
        })
        fileList.forEach((item) => {
          item.createDate = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
          item.createBy = this.$store.state.user.name
          this.dataListNew.push(item)
        })
        const isLt2M = file.size / 1024 / 1024 < 300
        if (isLt2M === false) {
          this.$message.error('文件大小不能超过 ' + 300 + 'M !')
          this.fileList = []
          this.filesArra2 = []
        }
      },
      async showFile (row) {
        await openWindowOnUrl(row)
      },
      // 排序
      sortChangeHandle (column) {
        this.orders = []
        if (column.order != null) {
          this.orders.push({column: this.$utils.toLine(column.prop), asc: column.order === 'ascending'})
        }
        this.refreshList()
      },
      deleteMsgById (row, index) {
        this.dataListNew.splice(index, 1)
        if (row.id !== null && row.id !== '' && row.id !== undefined) {
          this.ossService.deleteMsgById(row.id)
        }
      },
      twoDecimalPlaces (num) {
        let str = num.toString()
        var len1 = str.substr(0, 1)
        var len2 = str.substr(1, 1)
        // eslint-disable-next-line eqeqeq
        if (str.length > 1 && len1 == 0 && len2 != '.') {
          str = str.substr(1, 1)
        }
        // eslint-disable-next-line eqeqeq
        if (len1 == '.') {
          str = ''
        }
        // eslint-disable-next-line eqeqeq
        if (str.indexOf('.') != -1) {
          var str_ = str.substr(str.indexOf('.') + 1)
          // eslint-disable-next-line eqeqeq
          if (str_.indexOf('.') != -1) {
            str = str.substr(0, str.indexOf('.') + str_.indexOf('.') + 1)
          }
          if (str_.length > 2) {
            this.$message.warning(`金额小数点后只能输入两位，请正确输入！`)
            return (str = '')
          }
        }
        // eslint-disable-next-line no-useless-escape
        str = str.replace(/[^\d^\.]+/g, '') // 保留数字和小数点
        return str
      },
      positiveInteger (num) {
        let str = num.toString()
        var len1 = str.substr(0, 1)
        var len2 = str.substr(1, 1)
        // eslint-disable-next-line eqeqeq
        if (str.length > 1 && len1 == 0 && len2 != '.') {
          str = str.substr(1, 1)
        }
        // eslint-disable-next-line eqeqeq
        if (len1 == '.') {
          str = ''
        }
        // eslint-disable-next-line no-useless-escape
        str = str.replace(/[^\d^]+/g, '') // 保留数字
        return str
      },
      tableRowClassName ({row, rowIndex}) {
        row.index = rowIndex
      },
      handleRadioChange (val) {
        if (val) {
          this.radio = val.index
        }
      },
      // 关闭窗口时调用
      closeXTable () {
        this.closePop()
      },
      rowStyle (event) {
        return 'cursor:pointer;'
      },
      closePop () {
        this.visable = false
      },
      updateStatusById (type) {
        if (type === 'agree') {
          this.inputForm.status = '5'
          this.contractInfoService.updateStatusById(this.inputForm)
        }
        // 驳回
        if (type === 'reject') {
          this.inputForm.status = '4'
          this.contractInfoService.updateStatusById(this.inputForm)
        }
        if (type === 'reback') {
          this.inputForm.status = '3'
          this.contractInfoService.updateStatusById(this.inputForm)
        }
      },
      checkData () {
        let begin = this.inputForm.effectiveDate
        let close = this.inputForm.closingDate
        if (close < begin) {
          this.$message.warning(`合同终止日期要大于合同开始日期`)
          this.inputForm.closingDate = ''
        }
      }
    }
  }
</script>

<style>
  .tid_40 .vxe-body--column .vxe-cell{
    padding: 1px;
    text-align: center;
  }
  .tid_40 .vxe-header--row .col--last{
    text-align: center;
  }
  .tid_45 .vxe-body--column .vxe-cell{
    padding: 1px;
    text-align: center;
  }
  .tid_45 .vxe-header--row .col--last{
    text-align: center;
  }
</style>

<style scoped>
  .avatar{
    height: 100px;
  }
  .el-divider__text {
    font-weight: bold;
    font-size: 16px;
  }
</style>
