<template>
  <div>
    <el-form size="middle" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="formReadOnly"
             label-width="200px" @submit.native.prevent>

      <el-divider content-position="left"><i class="el-icon-document"></i> 客户信息</el-divider>
      <el-row :gutter="0">
        <el-col :span="10">
          <el-form-item label="客户名称" prop="name" :rules="[
                   ]">
            <span slot="label"><span style="color: red;border-top: 20px">*</span> 客户名称</span>
            <el-input maxlength="64" v-model="inputForm.name" placeholder="请输入客户名称" clearable></el-input>
            <div class="usc_code_append_message">{{nameMessage}}</div>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-popover
            v-model="visiblePop"
            placement="left"
            width="400"
            height="800"
            trigger="click"
            :popper-options="{ boundariesElement: 'viewport', removeOnDestroy: true }"
            ref="pops">
            <vxe-table
              border="inner"
              auto-resize
              resizable
              :row-config="{isHover: true}"
              :data="gridData"
              :checkbox-config="{}"
              :row-style="rowStyle"
              :key="tableKey"
              @cell-click="rowClick"
              :show-header="false"
            >
              <vxe-column title="" field="entname" ></vxe-column>
            </vxe-table>
            <el-button type="info" slot="reference" @click="getPopTable" style="width: 100%" plain>查询</el-button>
          </el-popover>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否有统一社会信用代码" prop="isUscCode"
                        :rules="[
                          {required: true, message:'请选择是否有统一社会信用代码', trigger:'blur'}
                   ]">
            <el-radio-group v-model="inputForm.isUscCode">
              <el-radio v-for="item in $dictUtils.getDictList('yes_no')" :label="item.value" >{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col v-if="inputForm.isUscCode === '1'" :span="12">
            <el-form-item label="统一社会信用代码" prop="uscCode"
                          :rules="[
                                    {required: true, message:'统一社会信用代码不能为空', trigger:'blur'}
                     ]">
              <el-input v-model="inputForm.uscCode" placeholder="请填写统一社会信用代码" clearable></el-input>
              <div class="usc_code_append_message">{{uscCodeMessage}}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册地址" prop="companyAddress"
                          :rules="[
                     ]">
              <el-input v-model="inputForm.companyAddress" placeholder="注册地址" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="address"
                          :rules="[
                                  {required: true, message:'详细地址不能为空', trigger:'blur'}
                     ]">
              <el-input v-model="inputForm.address" placeholder="详细地址" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司电话" prop="mobile"
                          :rules="[
                     ]">
              <el-input v-model="inputForm.mobile" placeholder="公司电话" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks1"
                          :rules="[
                   ]">
              <el-input type="textarea" maxlength="500" v-model="inputForm.remarks1" placeholder="请填写备注" show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      <el-divider content-position="left"><i class="el-icon-document"></i> 合同信息</el-divider>
      <el-row  :gutter="0">
        <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="contractNo"
                        :rules="[
                 ]">
            <el-input :disabled="true" v-model="inputForm.contractNo" placeholder="自动生成" clearable></el-input>
          </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="effectiveDate"
                        :rules="[
               ]">
            <el-date-picker
              placement="bottom-start"
              value-format="yyyy-MM-dd"
              v-model="inputForm.effectiveDate"
              style="width: 100%"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同终止日期" prop="endTime"
                        :rules="[
               ]">
            <el-date-picker
              @change="checkFiledNo"
              placement="bottom-start"
              value-format="yyyy-MM-dd"
              v-model="inputForm.endTime"
              style="width: 100%"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks2"
                        :rules="[
                   ]">
            <el-input type="textarea" maxlength="500" v-model="inputForm.remarks2" placeholder="请填写备注" show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" type="border-card" @tab-click="tabHandleClick">
        <el-tab-pane label="客户联系人" name="contact">
          <span slot="label">客户联系人</span>
          <el-row :gutter="15">
            <el-button type="primary" style="margin-bottom: 15px" size="mini" :disabled="status === 'audit' || status === 'taskFormDetail'" @click="insertEvent('contact')">
              新增客户联系人
            </el-button>
          </el-row>
          <el-row  :gutter="15">
            <el-form :disabled="status === 'audit' || status === 'taskFormDetail'">
              <vxe-table
                border
                show-overflow
                show-footer
                :column-config="{resizable: true}"
                ref="contactTable"
                :key="tableKeyContact"
                class="vxe-table-element"
                :data="inputForm.cwProjectClientContactDTOList"
                style=""
                @cell-click=""
                @edit-closed=""
                highlight-current-row
                :edit-config="{trigger: 'click', mode: 'row', showStatus: false, autoClear: true, icon: '-'}"
              >
                <vxe-table-column align="center" field="name" title="姓名" :edit-render="{}">
                  <template v-slot:edit="scope">
                    <el-input v-model="scope.row.name" placeholder="姓名" clearable></el-input>
                  </template>
                </vxe-table-column>
                <vxe-table-column align="center" field="position" title="职务" :edit-render="{}">
                  <template v-slot:edit="scope">
                    <el-input v-model="scope.row.position" placeholder="职务" clearable></el-input>
                  </template>
                </vxe-table-column>
                <vxe-table-column align="center" field="contactFirst" title="联系方式1" :edit-render="{}">
                  <template v-slot:edit="scope">
                    <el-input v-model="scope.row.contactFirst" oninput="value=value.replace(/[^\d]/g,'')" placeholder="联系方式1" clearable></el-input>
                  </template>
                </vxe-table-column>
                <vxe-table-column align="center" field="contactSecond" title="联系方式2" :edit-render="{}">
                  <template v-slot:edit="scope">
                    <el-input v-model="scope.row.contactSecond" oninput="value=value.replace(/[^\d]/g,'')" placeholder="联系方式2" clearable></el-input>
                  </template>
                </vxe-table-column>
                <vxe-table-column align="center" field="remarks" title="备注" :edit-render="{}">
                  <template v-slot:edit="scope">
                    <el-input maxlength="500" v-model="scope.row.remarks" 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,'contact')">删除</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-form>
  </div>
</template>

<script>
  import EnterpriseSearchService from '@/api/cw/common/EnterpriseSearchService'
  import WorkClientService from '@/api/cw/workClientInfo/WorkClientService'
  import UserSelect from '@/components/userSelect'
  import CommonApi from '@/api/cw/common/CommonApi'
  import MaterialManagementService from '@/api/materialManagement/MaterialManagementService'
  import ContractService from '@/api/materialManagement/ContractService'
  import UpLoadComponent from '@/views/common/UpLoadComponent'
  import SelectUserTree from '@/views/modules/utils/treeUserSelect'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import UserService from '@/api/sys/UserService'
  export default {
    data () {
      return {
        validRules: {
          purchaserAgent: [
            {required: true, message: '采购人不能为空'}
          ],
          procurementOffice: [
            {required: true, message: '采购部门不能为空'}
          ],
          procurementType: [
            {required: true, message: '采购类型不能为空'}
          ]
        },
        title: '',
        method: '',
        visible: false,
        loading: false,
        indexRow: '',
        inputForm: {
          id: '',
          createDate: '',
          name: '',
          uscCode: '',
          isUscCode: '',
          address: '',
          companyAddress: '',
          mobile: '',
          remarks1: '',
          remarks2: '',
          contractName: '',
          signingDate: '',
          effectiveDate: '',
          endTime: '',
          cwProjectClientContactDTOList: [],
          files: [] // 附件信息
        },
        activeName: 'contact',
        uscCodeMessage: '',
        nameMessage: '',
        tableKey: '',
        tableKeyContact: '2',
        keyWatch: '',
        visiblePop: false,
        gridData: []
      }
    },
    enterpriseSearchService: null,
    workClientService: null,
    materialManagementService: null,
    contractService: null,
    userService: null,
    commonApi: null,
    created () {
      this.enterpriseSearchService = new EnterpriseSearchService()
      this.workClientService = new WorkClientService()
      this.materialManagementService = new MaterialManagementService()
      this.contractService = new ContractService()
      this.userService = new UserService()
      this.commonApi = new CommonApi()
    },
    props: {
      businessId: {
        type: String,
        default: ''
      },
      formReadOnly: {
        type: Boolean,
        default: false
      },
      status: {
        type: String,
        default: ''
      }
    },
    components: {
      UserSelect,
      UpLoadComponent,
      SelectUserTree,
      SelectTree
    },
    computed: {
      bus: {
        get () {
          return this.businessId
        },
        set (val) {
          this.businessId = val
        }
      },
      name () {
        return JSON.parse(localStorage.getItem('user')).name
      },
      officeName () {
        return JSON.parse(localStorage.getItem('user')).officeDTO.name
      },
      purchaserAgentId () {
        return JSON.parse(localStorage.getItem('user')).id
      },
      procurementTypeId () {
        return ''
      }
    },
    watch: {
      'keyWatch': {
        handler (newVal) {
          if (this.commonJS.isNotEmpty(this.bus)) {
            this.init('', this.bus)
          } else {
            this.$nextTick(() => {
              this.$refs.inputForm.resetFields()
              if (this.commonJS.isEmpty(this.inputForm.isUscCode)) {
                this.inputForm.isUscCode = '1'
              }
            })
          }
        }
      }
    },
    methods: {
      getKeyWatch (keyWatch) {
        this.keyWatch = keyWatch
      },
      init (method, id) {
        this.method = method
        this.inputForm = {
          id: '',
          createDate: '',
          name: '',
          isUscCode: '',
          mobile: '',
          uscCode: '',
          address: '',
          companyAddress: '',
          remarks1: '',
          remarks2: '',
          contractName: '',
          contractNo: '',
          signingDate: '',
          effectiveDate: '',
          endTime: '',
          cwProjectClientContactDTOList: [],
          files: [] // 附件信息
        }
        this.activeName = 'contact'
        this.uscCodeMessage = ''
        this.nameMessage = ''
        if (method === 'add') {
          this.title = `新建采购类型`
        } else if (method === 'edit') {
          this.title = '修改采购类型'
        }
        this.inputForm.id = id
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          if (this.formReadOnly === true && this.businessId !== 'false') {
            method = 'view'
          }
          if (this.commonJS.isEmpty(this.inputForm.handledByOffice)) {
            this.inputForm.handledByOffice = JSON.parse(localStorage.getItem('user')).officeDTO.id
          }
          if (this.status === 'audit' || this.status === 'taskFormDetail') {
            method = 'view'
          }
          this.loading = true
          this.$refs.inputForm.resetFields()
          this.contractService.findById(this.inputForm.id).then(({data}) => {
            if (this.inputForm.id !== 'false') {
              this.inputForm = this.recover(this.inputForm, data)
              this.$refs.uploadComponent.newUpload(method, this.inputForm.files, 'reimbursement')
              this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
              this.loading = false
            } else {
              this.inputForm.cwProjectClientContactDTOList = []
              this.loading = false
            }
          })
          if (method !== 'edit' && method !== 'view') {
            this.$refs.uploadComponent.newUpload(method, [], 'reimbursement')
          }
        })
      },
      // 表单提交
      doSubmit () {
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            if (this.$refs.uploadComponent.checkProgress()) {
              this.loading = false
              return
            }
            if (this.commonJS.isEmpty(this.inputForm.files)) {
              this.inputForm.files = []
            }
            this.inputForm.id = this.businessId
            this.inputForm.files = this.$refs.uploadComponent.getDataList()
            this.contractService.save(this.inputForm).then(({data}) => {
              this.close()
              this.$message.success(data)
              this.$emit('refreshDataList')
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          }
        })
      },
      close () {
        this.$refs.inputForm.resetFields()
        this.inputForm.detailInfos = []
        this.$refs.uploadComponent.clearUpload()
        this.visible = false
        this.nameMessage = ''
        this.uscCodeMessage = ''
      },
      reapplyForm (callback) {
        this.contractService.findById(this.inputForm.id).then(({data}) => {
          if (data.status !== '4') { // 审核状态不是“驳回”，就弹出提示
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
          } else {
            this.startForm(callback)
          }
        })
      },
      // 暂存
      async saveForm (callback) {
        this.loading = true
        if (this.$refs.uploadComponent.checkProgress()) {
          this.loading = false
          return
        }
        if (this.commonJS.isEmpty(this.inputForm.files)) {
          this.inputForm.files = []
        }
        this.inputForm.files = this.$refs.uploadComponent.getDataList()
        this.inputForm.status = '1'
        this.contractService.save(this.inputForm).then(({data}) => {
          callback()
          this.$refs.inputForm.resetFields()
          this.loading = false
        }).catch(() => {
          this.$refs.inputForm.resetFields()
          this.loading = false
        })
      },
      // 送审
      async startForm (callback) {
        this.$refs['inputForm'].validate(async (valid) => {
          if (valid) {
            this.loading = true
            if (this.$refs.uploadComponent.checkProgress()) {
              this.loading = false
              return
            }
            if (this.commonJS.isEmpty(this.inputForm.files)) {
              this.inputForm.files = []
            }
            if (this.commonJS.isEmpty(this.inputForm.cwProjectClientContactDTOList)) {
              this.$message.error('最少添加一个联系人')
              this.loading = false
              throw new Error()
            }
            this.inputForm.files = this.$refs.uploadComponent.getDataList()
            this.inputForm.status = '2'
            this.contractService.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
            })
          }
        })
      },
      // 通过
      async agreeForm (callback) {
        this.$refs['inputForm'].validate(async (valid) => {
          if (valid) {
            this.loading = true
            if (this.$refs.uploadComponent.checkProgress()) {
              this.loading = false
              return
            }
            if (this.commonJS.isEmpty(this.inputForm.files)) {
              this.inputForm.files = []
            }
            this.inputForm.files = this.$refs.uploadComponent.getDataList()
            this.inputForm.status = '5'
            this.contractService.save(this.inputForm).then(({data}) => {
              callback(data.businessTable, data.businessId, this.inputForm)
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
            // this.commonApi.getTaskNameByProcInsId(this.inputForm.procInsId).then(({data}) => {
            //   if (this.commonJS.isNotEmpty(data)) {
            //     console.log('进来了', data)
            //     if (data === '公司领导审批') {
            //       this.inputForm.status = '5'
            //     }
            //   }
            //   this.contractService.save(this.inputForm).then(({data}) => {
            //     callback(data.businessTable, data.businessId, this.inputForm)
            //     this.loading = false
            //   }).catch(() => {
            //     this.loading = false
            //   })
            // })
          }
        })
      },
      async updateStatusById (type, callback) {
        if (await this.$refs.uploadComponent.checkProgress()) {
          this.loading = false
          throw new Error()
        } else {
          if (type === 'reject' || type === 'reback') {
            this.contractService.findById(this.inputForm.id).then(({data}) => {
              if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
                this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                throw new Error()
              } else {
                if (type === 'reject') {
                  // 驳回
                  this.inputForm.status = '4'
                }
                if (type === 'reback') {
                  // 撤回
                  this.inputForm.status = '3'
                }
                if (type === 'reject' || type === 'reback') {
                  let param = {status: this.inputForm.status, id: this.inputForm.id}
                  this.contractService.updateStatusById(param).then(() => {
                    callback()
                  })
                }
              }
            })
          } else if (type === 'hold') {
            this.contractService.findById(this.inputForm.id).then(({data}) => {
              if (data.status !== '4') { // status的值不等于“驳回”就弹出提示
                this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                throw new Error()
              } else {
                // 终止
                let param = {status: '1', id: this.inputForm.id}
                this.contractService.updateStatusById(param).then(() => {
                  callback()
                })
              }
            })
          }
        }
      },
      async getPopTable () {
        let name = this.inputForm.name
        if (this.commonJS.isNotEmpty(name)) {
          await this.enterpriseSearchService.enterpriseSearchByName(name).then(({data}) => {
            this.gridData = data.data.items
            this.$refs.pops.updatePopper()
            this.tableKey = Math.random()
          })
        }
        this.$refs.pops.updatePopper()
      },
      closePop () {
        this.visiblePop = false
      },
      rowStyle (event) {
        return 'cursor:pointer;'
      },
      async rowClick (event) {
        let id = this.gridData[event.rowIndex].companyid
        await this.enterpriseSearchService.enterpriseTicketInfo(id).then((data) => {
          this.inputForm.name = data.data.ENTNAME
          this.inputForm.uscCode = data.data.UNCID
          this.inputForm.address = data.data.OPLOC
        })
        this.visiblePop = false
      },
      tabHandleClick (event) {
        // console.log(event)
      },
      insertEvent (type) {
        if (type === 'contact') {
          let d = {
            contactFirst: '',
            contactSecond: '',
            email: '',
            fax: '',
            name: '',
            officeId: '',
            position: '',
            remarks: '',
            sex: ''
          }
          if (this.commonJS.isEmpty(this.inputForm.cwProjectClientContactDTOList)) {
            this.inputForm.cwProjectClientContactDTOList = []
          }
          this.$refs.contactTable.insertAt(d)
          this.inputForm.cwProjectClientContactDTOList.push(d)
          this.tableKeyContact = Math.random()
        }
      },
      // 删除
      removeEvent (row, rowIndex, type) {
        if (type === 'contact') {
          this.$refs.contactTable.remove(row)
          this.inputForm.cwProjectClientContactDTOList.splice(rowIndex, 1)
        }
      },
      checkFiledNo () {
        console.log('进来了时间比较')
        // eslint-disable-next-line no-unused-vars
        let date1 = this.inputForm.effectiveDate
        // eslint-disable-next-line no-unused-vars
        let date2 = this.inputForm.endTime
        if (Date.parse(this.inputForm.endTime) < Date.parse(this.inputForm.effectiveDate)) {
          this.$message.warning(`合同终止日期要大于合同生效日期`)
          this.inputForm.endTime = ''
        }
      }
    }
  }
</script>
<style scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
</style>
<style>
  .usc_code_append_message {
    color: #F56C6C;
    font-size: 12px;
    line-height: 1;
    padding-top: 4px;
    position: absolute;
    top: 100%;
    left: 0;
  }
</style>
