<template>
  <div class="app-container">
    <div v-show="viewState == 1">
      <div class="tab-header webtop">
        <div>{{ viewTitle }}</div>
        <div>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="saveOrUpdate()">保存</el-button>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="submit()">提交</el-button>
          <el-button type="info" size="small" @click="handleReturn()">关闭</el-button>
        </div>
      </div>
      <div class="listconadd">
        <el-form ref="form_obj" :model="formobj" :rules="rules" class="formaddcopy02">
          <el-row style="border-top: 1px solid #e0e3eb">
            <el-col :span="8">
              <div class="span-sty">申请部门</div>
              <el-form-item><span class="addinputInfo">{{ formobj.dept }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">申请人</div>
              <el-form-item><span class="addinputInfo">{{ formobj.applyName }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">申请日期</div>
              <el-form-item><span class="addinputInfo">{{ formobj.applyDate }}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <div class="span-sty">客户名称</div>
              <el-form-item><span class="addinputInfo">{{ formobj.customer }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">贷款人</div>
              <el-form-item><span class="addinputInfo">{{ formobj.borrowerName }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">贷款合同编号</div>
              <el-form-item><span class="addinputInfo">{{ formobj.loanContractNo }}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <div class="span-sty">资方</div>
              <el-form-item><span class="addinputInfo">{{ formobj.bankName }}</span></el-form-item>
            </el-col>
            <el-col :span="16">
              <div class="span-sty">资方合同编号</div>
              <el-form-item><span class="addinputInfo">{{ formobj.bankContractNo }}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <div class="span-sty">原车主是否同意</div>
              <el-form-item>
                <el-radio-group class="addinputInfo" style="font-size: 1px" v-model="formobj.agree">
                  <el-radio label="是">是</el-radio>
                  <el-radio label="否">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <div class="span-sty">二次转租价格</div>
              <el-form-item><el-input class="addinputInfo" style="width: 20%" @keyup.native="UpNumber" v-model="formobj.amount" clearable placeholder=""/></el-form-item>
            </el-col>
          </el-row>
          <div class="title">
            <div>二次销售车辆列表(含主车、挂车)</div>
          </div>
          <el-table :key="tableKey" :data="formobj.vinList" :index="index" border style="width: 100%">
            <el-table-column fixed width="80" label="序号" type="index" :index="index + 1" align="center"/>
            <el-table-column fixed label="操作" width="80" align="center">
              <template slot-scope="scope">
                <el-button size="small" v-if="scope.row.vehType !== '主车'" type="danger" @click="handleDelete(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="vinNo" label="车架号" align="center" min-width="100" />
            <el-table-column prop="vehMark" label="车牌号" align="center" min-width="100"/>
            <el-table-column prop="vehType" label="车辆类型" align="center" min-width="120"/>
            <el-table-column prop="vehModel" label="车型" align="center" min-width="130"/>
          </el-table>
          <div class="title">新车主信息</div>
          <el-row>
            <el-col :span="24">
              <div class="span-sty">客户名称</div>
              <el-form-item>
                <el-select v-model="formobj.newCustomerSid" class="addinputInfo" filterable clearable placeholder="" @change="changeCustomer">
                  <el-option v-for="item in customer_list" :key="item.newCustomerSid" :label="item.vinOwner" :value="item.newCustomerSid"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <div class="span-sty">新车主名称</div>
              <el-form-item><el-input class="addinputInfo" style="width: 40%" v-model="formobj.vinOwner" clearable placeholder=""/></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">客户类型</div>
              <el-form-item>
                <el-select class="addinputInfo" v-model="formobj.customerTypeKey" placeholder="请选择" clearable filterable @change="customerTypeChange">
                  <el-option v-for="item in customerType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">联系电话</div>
              <el-form-item><el-input class="addinputInfo" style="width: 40%" v-model="formobj.phoneNum" clearable placeholder=""/></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <div class="span-sty">证件类型</div>
              <el-form-item>
                <el-select class="addinputInfo" v-model="formobj.certificateTypeKey" placeholder="请选择" clearable filterable @change="certificateTypeChange">
                  <el-option v-for="item in certificateType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">证件号码</div>
              <el-form-item><el-input class="addinputInfo" style="width: 40%" v-model="formobj.idNumber" clearable placeholder=""/></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">证件有效期</div>
              <el-form-item>
                <el-date-picker class="addinputInfo" style="width: 40%" v-model="formobj.endDate" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date" placeholder="选择日期"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="span-sty">证件地址</div>
              <el-form-item><el-input class="addinputInfo" style="width: 40%" v-model="formobj.cardAddress" clearable placeholder=""/></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="span-sty">转租方案说明</div>
              <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.plan" clearable placeholder=""/></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="span-sty">附件</div>
              <el-form-item>
                <uploadImg ref="uploadImg" class="addinputInfo" v-model="formobj.files" :limit="50" bucket="map" :upload-data="{ type: '0001' }"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import req from '@/api/secondarysublet/secondarysublet'
import uploadImg from '@/components/uploadFile/uploadImg'
import { typeValues, pickCustomer } from '@/api/Common/dictcommons'

export default {
  name: 'SecondarySubletAdd',
  components: {
    uploadImg
  },
  data() {
    return {
      viewTitle: '',
      viewState: 1,
      submitdisabled: false,
      tableKey: 1,
      index: 0,
      customerType_list: [],
      certificateType_list: [],
      customer_list: [],
      formobj: {
        sid: '',
        userSid: '',
        dept: '',
        deptSid: '',
        applyName: '',
        applyDate: '',
        orgPath: '',
        taskId: '',
        instanceId: '',
        loanContractNo: '',
        bankName: '',
        bankContractNo: '',
        customer: '',
        borrowerName: '',
        amount: '',
        plan: '',
        agree: '',
        vinOwner: '',
        customerTypeKey: '',
        customerType: '',
        phoneNum: '',
        cardAddress: '',
        endDate: '',
        idNumber: '',
        certificateTypeKey: '',
        certificateType: '',
        newCustomerSid: '',
        files: [],
        vinList: []
      },
      rules: {}
    }
  },
  methods: {
    UpNumber(e) {
      e.target.value = e.target.value.replace(/[^0-9.]/g, '') // 清除“数字”和“.”以外的字符
      e.target.value = e.target.value.replace(/^00/, '0.') // 开头不能有两个0
      e.target.value = e.target.value.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
      e.target.value = e.target.value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      e.target.value = e.target.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') // 只能输入两个小数
      if (e.target.value.indexOf('.') < 0 && e.target.value !== '' && e.target.value !== '-') {
        // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        e.target.value = parseFloat(e.target.value)
      }
    },
    init() {
      typeValues({ type: 'customerType' }).then((res) => {
        if (res.success) {
          this.customerType_list = res.data
        }
      })
      typeValues({ type: 'documenttype' }).then((res) => {
        if (res.success) {
          this.certificateType_list = res.data
        }
      })
      pickCustomer({ orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((res) => {
        if (res.success) {
          this.customer_list = res.data
        }
      })
    },
    showAdd(row) {
      this.viewTitle = '【新增】交回车辆二次转租申请'
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.init()
      req.init({ ledgerSid: row.ledgerSid }).then((resp) => {
        if (resp.success) {
          this.formobj = resp.data
          this.formobj.applyName = window.sessionStorage.getItem('name')
          this.formobj.dept = window.sessionStorage.getItem('defaultOrgPathName').substring(window.sessionStorage.getItem('defaultOrgPathName').lastIndexOf('/') + 1)
          this.formobj.deptSid = window.sessionStorage.getItem('defaultOrgPath').substring(window.sessionStorage.getItem('defaultOrgPath').lastIndexOf('/') + 1)
          this.formobj.userSid = window.sessionStorage.getItem('userSid')
          this.formobj.orgPath = window.sessionStorage.getItem('defaultOrgPath')
          var nowDate = new Date()
          var date = {
            year: nowDate.getFullYear(),
            month: nowDate.getMonth() + 1,
            day: nowDate.getDate()
          }
          this.formobj.applyDate = date.year + '-' + (date.month >= 10 ? date.month : '0' + date.month) + '-' + (date.day >= 10 ? date.day : '0' + date.day)
        }
      })
    },
    showEdit(row) {
      this.viewTitle = '【编辑】交回车辆二次转租申请'
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.init()
      req.fetchBySid({ sid: row.sid }).then((res) => {
        if (res.success) {
          this.formobj = res.data
        }
      })
    },
    customerTypeChange(value) {
      const choose = this.customerType_list.filter((item) => item.dictKey === value)
      if (choose.length > 0 && choose !== null) {
        this.formobj.customerType = choose[0].dictValue
      } else {
        this.formobj.customerType = ''
      }
    },
    certificateTypeChange(value) {
      const choose = this.certificateType_list.filter((item) => item.dictKey === value)
      if (choose.length > 0 && choose !== null) {
        this.formobj.certificateType = choose[0].dictValue
      } else {
        this.formobj.certificateType = ''
      }
    },
    handleDelete(index) {
      this.formobj.vinList.splice(index, 1)
    },
    changeCustomer(value) {
      const choose = this.customer_list.filter((item) => item.newCustomerSid === value)
      if (choose.length > 0 && choose !== null) {
        this.formobj.vinOwner = choose[0].vinOwner
        this.formobj.customerType = choose[0].customerType
        this.formobj.customerTypeKey = choose[0].customerTypeKey
        this.formobj.phoneNum = choose[0].phoneNum
        this.formobj.endDate = choose[0].endDate
        this.formobj.idNumber = choose[0].idNumber
        this.formobj.certificateType = choose[0].certificateType
        this.formobj.certificateTypeKey = choose[0].certificateTypeKey
      } else {
        this.formobj.vinOwner = ''
        this.formobj.customerType = ''
        this.formobj.customerTypeKey = ''
        this.formobj.phoneNum = ''
        this.formobj.endDate = ''
        this.formobj.idNumber = ''
        this.formobj.certificateType = ''
        this.formobj.certificateTypeKey = ''
      }
    },
    saveOrUpdate() {
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.submitdisabled = true
          req.saveOrUpdate(this.formobj).then((res) => {
            if (res.success) {
              this.$message({ showClose: true, type: 'success', message: '保存成功' })
              this.handleReturn('true')
            } else {
              this.submitdisabled = false
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        }
      })
    },
    submit() {
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          this.submitdisabled = true
          req.submit(this.formobj).then((res) => {
            if (res.success) {
              this.$message({ showClose: true, type: 'success', message: '操作成功' })
              this.handleReturn('true')
            } else {
              this.submitdisabled = false
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        }
      })
    },
    handleReturn(isreload) {
      if (isreload === 'true') this.$emit('reloadlist')
      this.formobj = {
        sid: '',
        userSid: '',
        dept: '',
        deptSid: '',
        applyName: '',
        applyDate: '',
        orgPath: '',
        taskId: '',
        instanceId: '',
        loanContractNo: '',
        bankName: '',
        bankContractNo: '',
        customer: '',
        borrowerName: '',
        amount: '',
        plan: '',
        agree: '',
        vinOwner: '',
        customerTypeKey: '',
        customerType: '',
        phoneNum: '',
        cardAddress: '',
        endDate: '',
        idNumber: '',
        certificateTypeKey: '',
        certificateType: '',
        newCustomerSid: '',
        files: [],
        vinList: []
      }
      this.submitdisabled = false
      this.$emit('doback')
    }
  }
}
</script>

<style scoped>
.span-sty {
  width: 150px !important;
}
.addinputInfo {
  margin-left: 140px !important;
}
</style>
