<template>
  <div class="app-container">
    <div>
      <div class="tab-header webtop">
        <div>{{ viewTitle }}</div>
        <div>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="save()">保存</el-button>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="submit()">提交</el-button>
        </div>
      </div>
    </div>
    <div class="">
      <el-form ref="dataForm" :model="formobj" class="formaddcopy02" :rules="rules">
        <el-row style="border-top: 1px solid #DFE6EC">
          <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"><el-checkbox v-model="checked" @change="changeChecked" style="padding-right: 10px">同申请人</el-checkbox>销售部门</div>
            <el-form-item>
              <el-select v-model="formobj.salesDept" :disabled="checked" class="addinputInfo" filterable clearable placeholder="" @change="changeOrg">
                <el-option v-for="item in org_list" :key="item.orgDeptSid" :label="item.orgDeptName" :value="item.orgDeptName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="span-sty">销售专员</div>
            <el-form-item>
              <el-select class="addinputInfo" :disabled="checked" v-model="formobj.salesman" filterable clearable placeholder="" @change="changeStaff">
                <el-option v-for="item in staff_list" :key="item.staffSid" :label="item.staffName" :value="item.staffName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="span-sty">销售部经理</div>
            <el-form-item><span class="addinputInfo">{{ formobj.manage }}</span></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: 50%" v-model="formobj.remarks" clearable placeholder=""/>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">客户基本信息</div>
        <el-row>
          <el-col :span="16">
            <div class="span-sty">客户名称</div>
            <el-form-item>
              <el-select v-model="formobj.customer" class="addinputInfo" filterable clearable placeholder="" @change="changeCustomer">
                <el-option v-for="item in customer_list" :key="item.sid" :label="item.name" :value="item.name"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="span-sty">客户类型</div>
            <el-form-item><span class="addinputInfo">{{ formobj.customerType }}</span></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <div class="span-sty">联系电话</div>
            <el-form-item><span class="addinputInfo">{{ formobj.clientPhone }}</span></el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="span-sty">证件类型</div>
            <el-form-item><span class="addinputInfo">{{ formobj.documents }}</span></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <div class="span-sty"><span class="icon">*</span>证件号码</div>
            <el-form-item><el-input class="addinputInfo" style="width: 30%;" v-model="formobj.clientNo" clearable placeholder=""/></el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="span-sty">证件有效期</div>
            <el-form-item><el-date-picker class="addinputInfo" v-model="formobj.documentsDate" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="选择日期" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <div class="span-sty">证件地址</div>
            <el-form-item><el-input class="addinputInfo" style="width: 60%;" v-model="formobj.clientAddress" clearable placeholder=""/></el-form-item>
          </el-col>
          <el-col :span="8">
            <div v-show="formobj.customerTypeKey == '1'">
              <div class="span-sty"><span class="icon">*</span>是否挂靠运输公司</div>
              <el-form-item>
                <el-radio-group class="addinputInfo" style="font-size: 1px" v-model="formobj.isAnchored" @change="isAnchoredChange">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <div v-show="formobj.customerTypeKey === '2'">
          <div class="title titleOne">
            <div>企业人员信息</div>
            <el-button type="primary" size="mini" @click="addPerson">添加</el-button>
          </div>
          <el-table :key="tableKey" v-loading="listLoading" :data="formobj.staffs" :index="index" border style="width: 100%">
            <el-table-column fixed width="80px" label="序号" type="index" :index="index + 1" align="center"/>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="danger" size="mini" @click="deletePerson(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column label="姓名" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.name" clearable placeholder=""></el-input>
              </template>
            </el-table-column>
            <el-table-column label="身份" align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.identityValue" placeholder="请选择" @change="identityChange($event, scope.row)" clearable filterable>
                  <el-option v-for="item in identity_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictValue"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="手机号码" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.mobile" clearable placeholder=""></el-input>
              </template>
            </el-table-column>
            <el-table-column label="身份证号码" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.idNumber" clearable placeholder=""></el-input>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-show="formobj.customerTypeKey === '1' && formobj.isAnchored === '1'">
          <div class="title">挂靠运输公司信息</div>
          <el-row>
            <el-col :span="24">
              <div class="span-sty">选择挂靠运输公司</div>
              <el-form-item>
                <el-select v-model="formobj.businessName" class="addinputInfo" style="width: 30%" filterable clearable placeholder="" @change="changeBusiness">
                  <el-option v-for="item in business_list" :key="item.taxpayerNo" :label="item.businessName" :value="item.businessName"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <div class="span-sty"><span class="icon">*</span>企业名称</div>
              <el-form-item><el-input class="addinputInfo" style="width: 30%" v-model="formobj.businessName" clearable placeholder=""/></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty"><span class="icon">*</span>统一社会信用代码</div>
              <el-form-item><el-input class="addinputInfo" style="width: 50%" v-model="formobj.taxpayerNo" clearable placeholder=""/></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <div class="span-sty">负责人</div>
              <el-form-item><el-input class="addinputInfo" style="width: 30%" v-model="formobj.leader" clearable placeholder=""/></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">联系电话</div>
              <el-form-item><el-input class="addinputInfo" style="width: 50%" v-model="formobj.phone" clearable placeholder=""/></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <div class="span-sty">法定代表人</div>
              <el-form-item><el-input class="addinputInfo" style="width: 30%" v-model="formobj.legal" clearable placeholder=""/></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">证件地址</div>
              <el-form-item><el-input class="addinputInfo" style="width: 50%" v-model="formobj.address" clearable placeholder=""/></el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="title" :class="{titleOne:formobj.customerTypeKey === '2'}">
          <div>附件清单</div>
          <el-button type="primary" v-show="formobj.customerTypeKey === '2'" class="btntopblueline" size="mini" @click="downLoad('/template/信息查询授权书.pdf')">信息查询授权书模板下载</el-button>
        </div>
        <el-row v-show="formobj.customerTypeKey === '2' || (formobj.customerTypeKey === '1' && formobj.isAnchored === '1')">
          <el-col :span="24">
            <div class="span-sty span-sty-special" style="display: flex;flex-direction: row;justify-content: flex-end;align-items: center">营业执照</div>
            <el-form-item>
              <upload-img ref="uploadImg" class="addinputInfo addinputInfo-special" v-model="image_list1" :limit="50" bucket="map" :upload-data="{ type: '0001' }"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="formobj.customerTypeKey === '2' || (formobj.customerTypeKey === '1' && formobj.isAnchored === '0')">
          <el-col :span="24">
            <div class="span-sty span-sty-special" style="display: flex;flex-direction: row;justify-content: flex-end;align-items: center">
              <span v-show="formobj.customerTypeKey === '2'">法人和实际控制人身份证</span>
              <span v-show="formobj.customerTypeKey === '1' && formobj.isAnchored === '0'">本人身份证</span>
            </div>
            <el-form-item>
              <upload-img ref="uploadImg" class="addinputInfo addinputInfo-special" v-model="image_list2" :limit="50" bucket="map" :upload-data="{ type: '0001' }"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="formobj.customerTypeKey === '2'">
          <el-col :span="24">
            <div class="span-sty span-sty-special" style="display: flex;flex-direction: row;justify-content: flex-end;align-items: center">法人和实际控制人签署的《信息查询授权书》</div>
            <el-form-item>
              <upload-img ref="uploadImg" class="addinputInfo addinputInfo-special" v-model="image_list3" :limit="50" bucket="map" :upload-data="{ type: '0001' }"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="formobj.customerTypeKey === '1' && formobj.isAnchored === '1'">
          <el-col :span="24">
            <div class="span-sty span-sty-special" style="display: flex;flex-direction: row;justify-content: flex-end;align-items: center">车队挂靠协议</div>
            <el-form-item>
              <upload-img ref="uploadImg" class="addinputInfo addinputInfo-special" v-model="image_list4" :limit="50" bucket="map" :upload-data="{ type: '0001' }"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="span-sty span-sty-special" style="display: flex;flex-direction: row;justify-content: flex-end;align-items: center">其他资料</div>
            <el-form-item>
              <upload-img ref="uploadImg" class="addinputInfo addinputInfo-special" v-model="image_list5" :limit="50" bucket="map" :upload-data="{ type: '0001' }"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import req from '@/api/delinquentcustomerfiling/delinquentcustomerfiling'
import { selectOrgList, selectMangerByDeptSid, selectCustomerList, typeValues, selectInvoingByOrgPath } from '@/api/Common/dictcommons'
import uploadImg from '@/components/uploadFile/uploadImg'
import { getStorage } from '@/utils/auth'

export default {
  name: 'DelinquentCustomerFilingEdit',
  components: {
    uploadImg
  },
  data() {
    return {
      viewTitle: '',
      submitdisabled: false,
      tableKey: 0,
      index: 0,
      listLoading: false,
      checked: false,
      org_list: [],
      customer_list: [],
      identity_list: [],
      business_list: [],
      staff_list: [],
      image_list1: [],
      image_list2: [],
      image_list3: [],
      image_list4: [],
      image_list5: [],
      formobj: {
        sid: '',
        userSid: '',
        applyName: '',
        applyDate: '',
        salesmanSid: '',
        salesman: '',
        dept: '',
        deptSid: '',
        salesDept: '',
        salesDeptSid: '',
        manage: '',
        manageSid: '',
        isAnchored: '',
        customerSid: '',
        customer: '',
        customerTypeKey: '',
        customerType: '',
        clientPhone: '',
        clientNo: '',
        documents: '',
        documentsDate: '',
        clientAddress: '',
        businessName: '',
        taxpayerNo: '',
        address: '',
        phone: '',
        leader: '',
        legal: '',
        orgPath: '',
        staffs: [],
        license: [],
        idCard: [],
        infoLetter: [],
        agreement: [],
        otherInfo: [],
        taskId: '',
        instanceId: '',
        remarks: ''
      },
      rules: {}
    }
  },
  created() {
    console.log('url:' + window.location.href)
    var one = window.location.href.indexOf('&data') + 6
    const data = window.location.href.substr(one) // url解码unescape()已从web中移除,尽量不使用
    const obj = JSON.parse(decodeURIComponent(data))
    this.showInfo(obj.businessSid)
  },
  mounted() {
    window.parent.postMessage({
      cmd: 'returnHeight',
      params: {
        // 告诉父级页面，子页面的弹框高度。
        code: 2,
        data: 500 + 'px'
      }
    }, '*')
  },
  methods: {
    init() {
      typeValues({ type: 'identity' }).then((res) => {
        if (res.success) {
          this.identity_list = res.data
        }
      })
    },
    showInfo(sid) {
      this.viewTitle = '【编辑】欠款客户备案申请'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.init()
      req.fetchBySid(sid).then((res) => {
        if (res.success) {
          this.formobj = res.data
          this.selectOrg(this.formobj.userSid, this.formobj.orgPath)
          if (this.formobj.license.length > 0) {
            this.formobj.license.forEach((e) => {
              this.image_list1.push({
                name: '',
                url: e
              })
            })
          }
          if (this.formobj.idCard.length > 0) {
            this.formobj.idCard.forEach((e) => {
              this.image_list2.push({
                name: '',
                url: e
              })
            })
          }
          if (this.formobj.infoLetter.length > 0) {
            this.formobj.infoLetter.forEach((e) => {
              this.image_list3.push({
                name: '',
                url: e
              })
            })
          }
          if (this.formobj.agreement.length > 0) {
            this.formobj.agreement.forEach((e) => {
              this.image_list4.push({
                name: '',
                url: e
              })
            })
          }
          if (this.formobj.otherInfo.length > 0) {
            this.formobj.otherInfo.forEach((e) => {
              this.image_list5.push({
                name: '',
                url: e
              })
            })
          }
        }
      })
    },
    // 获取本分公司的销售部门
    selectOrg(userSid, orgSidPath) {
      selectOrgList({ userSid: userSid, orgPath: orgSidPath }).then((resp) => {
        if (resp.success) {
          this.org_list = resp.data
        }
      })
    },
    // 获取销售专员下的客户
    selectCustomer(userSid, staffSid, orgSidPath) {
      selectCustomerList({ userSid: userSid, staffSid: staffSid, orgPath: orgSidPath }).then((res) => {
        if (res.success) {
          this.customer_list = res.data
        }
      })
    },
    // 是否勾选同申请人--勾选是则销售部门、销售人员等信息与发起人信息一致
    changeChecked(val) {
      if (val) {
        this.formobj.salesDept = this.formobj.dept
        this.formobj.salesDeptSid = this.formobj.deptSid
        this.formobj.salesman = this.formobj.applyName
        this.formobj.salesmanSid = window.sessionStorage.getItem('staffSid')
        this.selectCustomer(this.formobj.userSid, this.formobj.salesmanSid, this.formobj.orgPath)
        selectMangerByDeptSid({ deptSid: this.formobj.deptSid }).then((res) => {
          if (res.success) {
            this.formobj.manage = res.data.manage
            this.formobj.manageSid = res.data.manageSid
          }
        })
      } else {
        this.formobj.salesDept = ''
        this.formobj.salesDeptSid = ''
        this.formobj.salesman = ''
        this.formobj.salesmanSid = ''
        this.formobj.manage = ''
        this.formobj.manageSid = ''
      }
    },
    // 选择销售部门
    changeOrg(value) {
      const choosetItem = this.org_list.filter((item) => item.orgDeptName === value)
      if (choosetItem.length > 0 && choosetItem !== null) {
        this.formobj.salesDeptSid = choosetItem[0].orgDeptSid
        this.staff_list = choosetItem[0].staffinfoVoList
        selectMangerByDeptSid({ deptSid: choosetItem[0].orgDeptSid }).then((res) => {
          if (res.success) {
            this.formobj.manage = res.data.manage
            this.formobj.manageSid = res.data.manageSid
          }
        })
      } else {
        // 销售部门置空时需置空部分信息
        this.formobj.salesDeptSid = ''
        // 销售专员
        this.formobj.salesman = ''
        this.formobj.salesmanSid = ''
        this.staff_list = []
        // 销售经理
        this.formobj.manage = ''
        this.formobj.manageSid = ''
      }
    },
    // 选择销售人员
    changeStaff(value) {
      const choosetItem = this.staff_list.filter((item) => item.staffName === value)
      if (choosetItem.length > 0 && choosetItem !== null) {
        this.formobj.salesmanSid = choosetItem[0].staffSid
        this.selectCustomer(this.formobj.userSid, this.formobj.salesmanSid, this.formobj.orgPath)
      } else {
        this.formobj.salesmanSid = ''
      }
    },
    // 选择客户
    changeCustomer(value) {
      const choosetItem = this.customer_list.filter((item) => item.name === value)
      if (choosetItem.length > 0 && choosetItem !== null) {
        this.formobj.customerSid = choosetItem[0].sid
        this.formobj.customerType = choosetItem[0].customerType
        this.formobj.customerTypeKey = choosetItem[0].customerTypeKey
        this.formobj.clientPhone = choosetItem[0].mobile
        this.formobj.documents = choosetItem[0].documents
        this.formobj.documentsDate = choosetItem[0].documentsDate
        this.formobj.clientNo = choosetItem[0].idCard
        this.formobj.clientAddress = choosetItem[0].clientAddress
      } else {
        this.formobj.customerSid = ''
        this.formobj.customerType = ''
        this.formobj.customerTypeKey = ''
        this.formobj.clientPhone = ''
        this.formobj.documents = ''
        this.formobj.documentsDate = ''
        this.formobj.clientNo = ''
        this.formobj.clientAddress = ''
      }
    },
    isAnchoredChange(val) {
      if (val === '1') {
        selectInvoingByOrgPath({ orgPath: this.formobj.orgPath }).then((res) => {
          if (res.success) {
            this.business_list = res.data
          }
        })
      }
    },
    addPerson() {
      this.formobj.staffs.push({
        name: '',
        identityKey: '',
        identityValue: '',
        mobile: '',
        idNumber: ''
      })
    },
    identityChange(value, row) {
      const choose = this.identity_list.filter((item) => item.dictValue === value)
      if (choose.length > 0) {
        row.identityKey = choose[0].dictKey
      } else {
        row.identityKey = ''
      }
    },
    deletePerson(index) {
      this.formobj.staffs.splice(index, 1)
    },
    changeBusiness(value) {
      const choose = this.business_list.filter((item) => item.businessName === value)
      if (choose.length > 0) {
        this.formobj.taxpayerNo = choose[0].taxpayerNo
        this.formobj.phone = choose[0].phone
        this.formobj.address = choose[0].address
      } else {
        this.formobj.taxpayerNo = ''
        this.formobj.phone = ''
        this.formobj.address = ''
      }
    },
    downLoad(filePath) {
      var xhr = new XMLHttpRequest()
      xhr.open('GET', process.env.VUE_APP_BASE_API + '/base/file/download?filePath=' + filePath + '&outFileName=' + '信息查询授权书', true)
      xhr.setRequestHeader('token', getStorage())
      xhr.responseType = 'blob'
      xhr.onload = function(e) {
        // 如果请求执行成功
        var blob = this.response
        var filename = '信息查询授权书.pdf'
        var a = document.createElement('a')
        // blob.type="application/octet-stream";
        // 创键临时url对象
        var url = URL.createObjectURL(blob)
        a.href = url
        a.download = filename
        a.click()
        // 释放之前创建的URL对象
        window.URL.revokeObjectURL(url)
      }
      // 发送请求
      xhr.send()
    },
    save() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.getUrl()
          this.submitdisabled = true
          req.saveOrUpdate(this.formobj).then((res) => {
            if (res.success) {
              this.$message({ showClose: true, type: 'success', message: '保存成功' })
              // 子页面向父级页面传递值(关闭弹框)
              window.parent.postMessage({
                cmd: 'returnHeight',
                params: {
                  // 操作成功，告诉父级页面关闭弹框
                  code: 1
                }
              }, '*')
            } else {
              this.submitdisabled = false
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        }
      })
    },
    submit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.formobj.customer === '') {
            this.$message({ showClose: true, type: 'error', message: '客户名称不能为空' })
            return
          }
          if (this.formobj.clientNo === '') {
            this.$message({ showClose: true, type: 'error', message: '证件号码不能为空' })
            return
          }
          if (this.formobj.customerTypeKey === '1') {
            if (this.formobj.isAnchored === '') {
              this.$message({ showClose: true, type: 'error', message: '是否挂靠运输公司请选择是或否' })
              return
            }
            if (this.formobj.isAnchored === '1' && (this.formobj.businessName === '' || this.formobj.taxpayerNo === '')) {
              this.$message({ showClose: true, type: 'error', message: '是否挂靠运输公司选则是的情况下,请完善挂靠运输公司信息' })
              return
            }
          }
          this.getUrl()
          this.submitdisabled = true
          req.submit(this.formobj).then((res) => {
            if (res.success) {
              this.$message({ showClose: true, type: 'success', message: '操作成功' })
              // 子页面向父级页面传递值(关闭弹框)
              window.parent.postMessage({
                cmd: 'returnHeight',
                params: {
                  // 操作成功，告诉父级页面关闭弹框
                  code: 1
                }
              }, '*')
            } else {
              this.submitdisabled = false
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        }
      })
    },
    getUrl() {
      if (this.image_list1.length > 0) {
        const aa = []
        this.image_list1.forEach((e) => {
          aa.push(e.url)
        })
        this.formobj.license = aa
      } else {
        this.formobj.license = []
      }
      if (this.image_list2.length > 0) {
        const aa = []
        this.image_list2.forEach((e) => {
          aa.push(e.url)
        })
        this.formobj.idCard = aa
      } else {
        this.formobj.idCard = []
      }
      if (this.image_list3.length > 0) {
        const aa = []
        this.image_list3.forEach((e) => {
          aa.push(e.url)
        })
        this.formobj.infoLetter = aa
      } else {
        this.formobj.infoLetter = []
      }
      if (this.image_list4.length > 0) {
        const aa = []
        this.image_list4.forEach((e) => {
          aa.push(e.url)
        })
        this.formobj.agreement = aa
      } else {
        this.formobj.agreement = []
      }
      if (this.image_list5.length > 0) {
        const aa = []
        this.image_list5.forEach((e) => {
          aa.push(e.url)
        })
        this.formobj.otherInfo = aa
      } else {
        this.formobj.otherInfo = []
      }
    }
  }
}
</script>

<style scoped>
.span-sty {
  width: 170px !important;
}
.addinputInfo {
  margin-left: 160px !important;
}
.span-sty-special {
  width: 300px !important;
}
.addinputInfo-special {
  margin-left: 290px !important;
}
.titleOne {
  padding: 7px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
</style>
