<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="info" size="small" @click="handleReturn()">关闭</el-button>
        </div>
      </div>
      <div class="listconadd">
        <el-form ref="form_obj" :model="formobj" :rules="rules" class="formaddcopy02">
          <div class="title">基本信息</div>
          <el-row style="border-top: 1px solid #e0e3eb">
            <el-col :span="8">
              <div class="span-sty"><span class="icon">*</span>供应商名称</div>
              <el-form-item prop="supplierName"><el-input class="addinputInfo addinputw" v-model="formobj.supplierName" clearable placeholder=""/></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty"><span class="icon">*</span>供应商简称</div>
              <el-form-item prop="supplierPY"><el-input class="addinputInfo addinputw" v-model="formobj.supplierPY" clearable placeholder=""/></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty"><span class="icon">*</span>供应商编码</div>
              <el-form-item prop="supplierCode"><el-input class="addinputInfo addinputw" v-model="formobj.supplierCode" clearable placeholder=""/></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <div class="span-sty"><span class="icon">*</span>供应商类型</div>
              <el-form-item prop="supplierTypeSid">
                <el-select class="addinputInfo" v-model="formobj.supplierTypeSid" filterable placeholder="" @change="supplierTypeChange">
                  <el-option v-for="item in supplierType_list" :key="item.sid" :label="item.supplierTypeName" :value="item.sid"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty"><span class="icon">*</span>供应商电话</div>
              <el-form-item prop="contactTelePhone"><el-input class="addinputInfo addinputw" v-model="formobj.contactTelePhone" clearable placeholder=""/></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">传真</div>
              <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.fax" clearable placeholder=""/></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="span-sty">详细地址</div>
              <el-form-item>
                <div class="addinputInfo" style="display: flex;flex-direction: row;justify-content: flex-start;align-items: center">
                  <el-select v-model="formobj.province" filterable clearable placeholder="请选择省" style="width:160px" @change="provinceChange">
                    <el-option v-for="item in province_list" :key="item.sid" :label="item.name" :value="item.name"/>
                  </el-select>
                  <el-select v-model="formobj.city" filterable placeholder="请选择市" style="width:160px" @change="cityChange">
                    <el-option v-for="item in city_list" :key="item.sid" :label="item.name" :value="item.name"/>
                  </el-select>
                  <el-select v-model="formobj.county" filterable placeholder="请选择县" style="width:160px" @change="countyChange">
                    <el-option v-for="item in county_list" :key="item.sid" :label="item.name" :value="item.name"/>
                  </el-select>
                  <el-input style="width: 30%" v-model="formobj.address" clearable placeholder=""/>
                </div>
              </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 addinputw" v-model="formobj.contactName" clearable placeholder=""/></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">联系电话</div>
              <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.contactMobile" clearable placeholder=""/></el-form-item>
            </el-col>
            <el-col :span="8">
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <div class="span-sty">邮编</div>
              <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.zipCode" clearable placeholder=""/></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">电子邮件</div>
              <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.email" clearable placeholder=""/></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">网址</div>
              <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.website" clearable placeholder=""/></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <div class="span-sty"><span class="icon">*</span>开票公司名称</div>
              <el-form-item prop="billingCompanyName"><el-input class="addinputInfo addinputw" v-model="formobj.billingCompanyName" clearable placeholder=""/></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">税号</div>
              <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.registNum" clearable placeholder=""/></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">法人</div>
              <el-form-item><el-input class="addinputInfo addinputw" v-model="formobj.legalName" clearable placeholder=""/></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 addinputw" v-model="formobj.purchaser" clearable placeholder=""/></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty"><span class="icon">*</span>开票类型</div>
              <el-form-item prop="billingTypeValue">
                <el-select class="addinputInfo" v-model="formobj.billingTypeValue" filterable placeholder="" @change="billingTypeChange">
                  <el-option v-for="item in billingType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictValue"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty"><span class="icon">*</span>税率</div>
              <el-form-item prop="taxRate"><el-input class="addinputInfo addinputw" @keyup.native="formobj.taxRate = getNumber(formobj.taxRate, 2)" v-model="formobj.taxRate" 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.remarks" clearable placeholder=""/></el-form-item>
            </el-col>
          </el-row>
          <div class="title titleOne">
            <div>开户行列表</div>
            <el-button type="primary" size="mini" class="btntopblueline" @click="handleAdd">新增</el-button>
          </div>
          <el-table :key="tableKey" :data="formobj.pmsSupplierBankList" :index="index" border style="width: 100%">
            <el-table-column fixed width="80" label="序号" type="index" :index="index + 1" align="center"/>
            <el-table-column fixed width="150" label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="handleEdit(scope.row, scope.$index)">编辑</el-button>
                <el-button type="danger" size="mini" @click="handleDelete(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="dueBankValue" label="账户类型" align="center" width="100" />
            <el-table-column prop="bankName" label="开户银行" align="center" width="120"/>
            <el-table-column prop="bankAccount" label="银行账号" align="center" width="100" />
            <el-table-column prop="accountName" label="账号名称" align="center" width="160" />
            <el-table-column prop="bankingOutlets" label="银行网点" align="center" width="100" />
            <el-table-column prop="bankAddress" label="开户行地址" align="center" min-width="200"/>
            <el-table-column prop="paymentLines" label="联行号" align="center" width="100"/>
            <el-table-column prop="swiftCode" label="swifcode(银行代码)" align="center" width="170" />
            <el-table-column prop="currency" label="币种" align="center" width="100"/>
          </el-table>
        </el-form>
      </div>
    </div>
    <openingbank v-show="viewState == 2 || viewState == 3" ref="divOpen" @backData="backData" @doback="resetState" />
  </div>
</template>

<script>
import req from '@/api/basicinformation/supplier'
import openingbank from './relation/openingbank'
import { getProvince, getCity, getCounty, typeValues } from '@/api/Common/dictcommons'

export default {
  name: 'SupplierAdd',
  components: {
    openingbank
  },
  data() {
    return {
      viewTitle: '',
      viewState: 1,
      submitdisabled: false,
      tableKey: 0,
      index: 0,
      supplierType_list: [],
      province_list: [],
      city_list: [],
      county_list: [],
      billingType_list: [],
      formobj: {
        sid: '',
        supplierCode: '',
        supplierName: '',
        supplierPY: '',
        supplierTypeSid: '',
        supplierTypeName: '',
        provinceSid: '',
        province: '',
        citySid: '',
        city: '',
        countySid: '',
        county: '',
        address: '',
        contactMobile: '',
        contactTelePhone: '',
        contactName: '',
        fax: '',
        zipCode: '',
        email: '',
        website: '',
        billingCompanyName: '',
        registNum: '',
        legalName: '',
        purchaser: '',
        sortNo: '',
        billingTypeKey: '',
        billingTypeValue: '',
        useOrgSid: '',
        createOrgName: '',
        createOrgSid: '',
        taxRate: '',
        remarks: '',
        pmsSupplierBankList: []
      },
      rules: {
        supplierName: [{ required: true, message: '供应商名称不能为空', trigger: 'blur' }],
        supplierPY: [{ required: true, message: '供应商简称不能为空', trigger: 'blur' }],
        supplierCode: [{ required: true, message: '供应商编码不能为空', trigger: 'blur' }],
        supplierTypeSid: [{ required: true, message: '供应商类型不能为空', trigger: 'change' }],
        contactTelePhone: [{ required: true, message: '供应商电话不能为空', trigger: 'blur' }],
        billingCompanyName: [{ required: true, message: '开票公司名称不能为空', trigger: 'blur' }],
        billingTypeValue: [{ required: true, message: '开票类型不能为空', trigger: 'change' }],
        taxRate: [{ required: true, message: '税率不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    init() {
      typeValues({ type: 'accountType' }).then((res) => {
        if (res.success) {
          this.billingType_list = res.data
        }
      })
      getProvince().then((res) => {
        if (res.success) {
          this.province_list = res.data
        }
      })
      req.selSupplierType({ orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((res) => {
        if (res.success) {
          this.supplierType_list = res.data
        }
      })
    },
    getNumber(val, limit) {
      val = val.replace(/[^0-9.]/g, '') // 保留数字
      val = val.replace(/^00/, '0.') // 开头不能有两个0
      val = val.replace(/^\./g, '0.') // 开头为小数点转换为0.
      val = val.replace(/\.{2,}/g, '.') // 两个以上的小数点转换成一个
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.'); // 只保留一个小数点
      /^0\d+/.test(val) ? val = val.slice(1) : '' // 两位以上数字开头不能为0
      const str = '^(\\d+)\\.(\\d{' + limit + '}).*$'
      const reg = new RegExp(str)
      if (limit === 0) {
        // 不需要小数点
        val = val.replace(reg, '$1')
      } else {
        // 通过正则保留小数点后指定的位数
        val = val.replace(reg, '$1.$2')
      }
      return val
    },
    supplierTypeChange(value) {
      const choose = this.supplierType_list.filter((item) => item.sid === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.supplierTypeName = choose[0].supplierTypeName
      }
    },
    provinceChange(value) {
      const choose = this.province_list.filter((item) => item.name === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.provinceSid = choose[0].sid
        this.getCity(this.formobj.provinceSid)
      } else {
        this.formobj.provinceSid = ''
        this.formobj.citySid = ''
        this.formobj.city = ''
        this.city_list = []
        this.formobj.county = ''
        this.formobj.countySid = ''
        this.county_list = []
      }
    },
    getCity(val) {
      getCity({ sid: val }).then((res) => {
        if (res.success) {
          this.city_list = res.data
        }
      })
    },
    cityChange(value) {
      const choose = this.city_list.filter((item) => item.name === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.citySid = choose[0].sid
        this.getCounty(this.formobj.citySid)
      }
    },
    getCounty(val) {
      getCounty({ sid: val }).then((res) => {
        if (res.success) {
          this.county_list = res.data
        }
      })
    },
    countyChange(value) {
      const choose = this.county_list.filter((item) => item.name === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.countySid = choose[0].sid
      }
    },
    showAdd() {
      this.viewTitle = '【新增】供应商'
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.init()
    },
    showEdit(row) {
      this.viewTitle = '【编辑】供应商'
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.init()
      req.fetchDetailsBySid(row.sid).then((res) => {
        if (res.success) {
          this.formobj = res.data
        }
      })
    },
    billingTypeChange(value) {
      const choose = this.billingType_list.filter((item) => item.dictValue === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.billingTypeKey = choose[0].dictKey
      }
    },
    handleAdd() {
      this.viewState = 2
      this.$refs['divOpen'].showAdd()
    },
    handleEdit(row, index) {
      this.viewState = 3
      this.$refs['divOpen'].showEdit(row, index)
    },
    handleDelete(index) {
      this.formobj.pmsSupplierBankList.splice(index, 1)
    },
    backData(value, index) {
      this.viewState = 1
      value = JSON.parse(JSON.stringify(value))
      if (index !== '' && index !== null) {
        this.formobj.pmsSupplierBankList[index] = {
          sid: value.sid,
          supplierSid: value.supplierSid,
          bankName: value.bankName,
          bankAccount: value.bankAccount,
          accountName: value.accountName,
          dueBankKey: value.dueBankKey,
          dueBankValue: value.dueBankValue,
          bankingOutlets: value.bankingOutlets,
          bankAddress: value.bankAddress,
          paymentLines: value.paymentLines,
          swiftCode: value.swiftCode,
          currency: value.currency
        }
      } else {
        this.formobj.pmsSupplierBankList.push({
          sid: '',
          supplierSid: value.supplierSid,
          bankName: value.bankName,
          bankAccount: value.bankAccount,
          accountName: value.accountName,
          dueBankKey: value.dueBankKey,
          dueBankValue: value.dueBankValue,
          bankingOutlets: value.bankingOutlets,
          bankAddress: value.bankAddress,
          paymentLines: value.paymentLines,
          swiftCode: value.swiftCode,
          currency: value.currency
        })
      }
    },
    resetState() {
      this.viewState = 1
    },
    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
          })
        }
      })
    },
    handleReturn(isreload) {
      if (isreload === 'true') this.$emit('reloadlist')
      this.formobj = {
        sid: '',
        supplierCode: '',
        supplierName: '',
        supplierPY: '',
        supplierTypeSid: '',
        supplierTypeName: '',
        provinceSid: '',
        province: '',
        citySid: '',
        city: '',
        countySid: '',
        county: '',
        address: '',
        contactMobile: '',
        contactTelePhone: '',
        contactName: '',
        fax: '',
        zipCode: '',
        email: '',
        website: '',
        billingCompanyName: '',
        registNum: '',
        legalName: '',
        purchaser: '',
        sortNo: '',
        billingTypeKey: '',
        billingTypeValue: '',
        useOrgSid: '',
        createOrgName: '',
        createOrgSid: '',
        taxRate: '',
        remarks: '',
        pmsSupplierBankList: []
      }
      this.submitdisabled = false
      this.$emit('doback')
    }
  }
}
</script>

<style scoped>
.span-sty {
  width: 130px !important;
}
.addinputInfo {
  margin-left: 120px !important;
}
.formaddcopy02 .el-row .el-col /deep/ .el-form-item .addinputw {
  margin-left: 120px !important;
  width: calc(100% - 115px);
}
/deep/ .el-form-item__error {
  margin-left: 120px !important;
}
.titleOne {
  padding: 7px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
/*表格列设置fixed后固定列出现下边框的设置*/
/deep/ .el-table__fixed {
  height: 100% !important;
}
/*表格列设置fixed后固定列出现下边框的设置*/
/deep/ .el-table__fixed-right {
  height: 100% !important;
}
</style>
