<template>
  <div class="app-container">
    <el-form ref="elForm" :model="formData" :rules="rules" inline size="small" label-width="100px"
      label-position="left">
      <div>
        <el-form-item :label="$t('公司全称')" prop="companyZh">
          <el-input v-model="formData.companyZh" :placeholder="$t('请输入公司全称')" show-word-limit clearable></el-input>
        </el-form-item>
        <el-form-item :label="$t('英文名称')" prop="companyEn">
          <el-input v-model="formData.companyEn" :placeholder="$t('请输入公司英文名')" show-word-limit clearable></el-input>
        </el-form-item>
      </div>
      <div>
        <el-form-item :label="$t('合作开始时间')" prop="cooperationDateStart">
          <el-date-picker v-model="formData.cooperationDateStart" value-format="yyyy-MM-dd HH:mm:ss" clearable></el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('合作结束时间')" prop="cooperationDateEnd">
          <el-date-picker v-model="formData.cooperationDateEnd" value-format="yyyy-MM-dd HH:mm:ss" clearable></el-date-picker>
        </el-form-item>
      </div>
      <div>
        <el-form-item :label="$t('公司电话')" prop="tell">
          <el-input v-model="formData.tell" :placeholder="$t('请输入公司电话')" clearable></el-input>
        </el-form-item>
        <el-form-item :label="$t('邮件地址')" prop="email">
          <el-input v-model="formData.email" :placeholder="$t('请输入邮箱地址')" clearable></el-input>
        </el-form-item>
      </div>
      <div>
        <el-form-item :label="$t('公司地址')" prop="address">
          <area-selector
            :country="formData.country"
            :province="formData.province"
            :city="formData.city"
            @countryChange="onAreaChange('country', $event)"
            @provinceChange="onAreaChange('province', $event)"
            @cityChange="onAreaChange('city', $event)"
          />
          <el-input v-model="formData.address" :placeholder="$t('请输入详细地址')" class="mt-10"></el-input>
        </el-form-item>
      </div>
      <div>
        <el-form-item :label="$t('备注')" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :placeholder="$t('请输入备注')"
            :autosize="{minRows: 4, maxRows: 4}" class="w-500"></el-input>
        </el-form-item>
      </div>
      
      <div>
        <el-form-item :label="$t('供应商类别')" prop="companyType">
          <dict-selector v-model="formData.companyTypeArr" type="company_type" multiple />
        </el-form-item>
        <el-form-item :label="$t('合作类型')" prop="cooperationType">
          <dict-selector v-model="formData.cooperationType" type="cooperation_type" />
        </el-form-item>
      </div>
      
      <div>
        <el-form-item :label="$t('营业执照')" prop="license">
          <upload v-model="formData.license" />
        </el-form-item>
        <el-form-item :label="$t('合同')" prop="contract">
            <upload v-model="formData.contract" />
        </el-form-item>
      </div>
      <div>
        <el-form-item :label="$t('统一信用代码')" prop="licenseNumber">
          <el-input v-model="formData.licenseNumber" :placeholder="$t('请输入统一社会信用代码')" clearable
            :style="{width: '100%'}"></el-input>
        </el-form-item>
      </div>
      <el-card>
        <div class="card-header" slot="header">
          <div class="title">{{$t('联系人')}}</div>
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="formData.contactList.push({})"></el-button>
        </div>
        <el-table :data="formData.contactList" border class="data-list">
          <el-table-column :label="$t('序号')" width="80px">
            <template slot-scope="scope">{{scope.$index + 1}}</template>
          </el-table-column>
          <el-table-column :label="$t('部门')">
            <template slot-scope="scope">
              <el-input v-model="scope.row.department" placeholder=""></el-input>
            </template>
          </el-table-column>
          <el-table-column :label="$t('职位')">
            <template slot-scope="scope">
              <el-input v-model="scope.row.position" placeholder=""></el-input>
            </template>
          </el-table-column>
          <el-table-column :label="$t('名称') + '*'">
            <template slot="header">
              {{$t('名称')}}<span class="red">*</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                class="mb-0 mr-0"
                :prop="`contactList.${scope.$index}.name`"
                :rules="{required: true, message: $t('联系人名称不能为空'), trigger: 'blur'}"
              >
                <el-input v-model="scope.row.name"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('电话') + '*'">
            <template slot="header">
              {{$t('电话')}}<span class="red">*</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                class="mb-0 mr-0"
                :prop="`contactList.${scope.$index}.phone`"
                :rules="{required: true, message: $t('联系人电话不能为空'), trigger: 'blur'}"
              >
                <el-input v-model="scope.row.phone"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('操作')" width="80px">
            <template slot-scope="scope">
              <el-button type="danger" size="mini" @click="delContact(scope.$index)" icon="el-icon-delete"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-card class="mt-10">
        <div class="card-header" slot="header">
          <div class="title">{{$t('银行信息')}}</div>
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="formData.bankList.push({})"></el-button>
        </div>
        <el-table :data="formData.bankList" border class="data-list">
          <el-table-column :label="$t('序号')" width="80px">
            <template slot-scope="scope">{{scope.$index + 1}}</template>
          </el-table-column>
          <el-table-column :label="$t('账户名称') + '*'">
            <template slot="header">
              {{$t('账户名称')}}<span class="red">*</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                class="mb-0 mr-0"
                :prop="`bankList.${scope.$index}.accountName`"
                :rules="{required: true, message: $t('银行账户名称不能为空'), trigger: 'blur'}"
              >
                <el-input v-model="scope.row.accountName" placeholder=""></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('币别') + '*'">
            <template slot="header">
              {{$t('币别')}}<span class="red">*</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                class="mb-0 mr-0"
                :prop="`bankList.${scope.$index}.currency`"
                :rules="{required: true, message: $t('币别不能为空'), trigger: 'blur'}"
              >
                <selector :options="currencyList" v-model="scope.row.currency" value-field="id" :label-field="'title' + $l()"></selector>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('银行名称') + '*'">
            <template slot="header">
              {{$t('银行名称')}}<span class="red">*</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                class="mb-0 mr-0"
                :prop="`bankList.${scope.$index}.bankName`"
                :rules="{required: true, message: $t('银行名称不能为空'), trigger: 'blur'}"
              >
                <el-input v-model="scope.row.bankName"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('银行账户') + '*'">
            <template slot="header">
              {{$t('银行账户')}}<span class="red">*</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                class="mb-0 mr-0"
                :prop="`bankList.${scope.$index}.bankAccount`"
                :rules="{required: true, message: $t('银行账户不能为空'), trigger: 'blur'}"
              >
                <el-input v-model="scope.row.bankAccount"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('银行代码')">
            <template slot-scope="scope">
              <el-input v-model="scope.row.bankCode" placeholder=""></el-input>
            </template>
          </el-table-column>
          <el-table-column :label="$t('账户类型')">
            <template slot-scope="scope">
              <el-input v-model="scope.row.accountType" placeholder=""></el-input>
            </template>
          </el-table-column>
          <el-table-column :label="$t('状态')">
            <template slot-scope="scope">
              <dict-selector :type="DICT_TYPE.COMMON_STATUS" v-model="scope.row.status" defaultable />
            </template>
          </el-table-column>
          <el-table-column :label="$t('银行地址')">
            <template slot-scope="scope">
              <el-input v-model="scope.row.bankAddress" placeholder=""></el-input>
            </template>
          </el-table-column>
          <el-table-column :label="$t('操作')" width="80px">
            <template slot-scope="scope">
              <el-button type="danger" size="mini" @click="delBank(scope.$index)" icon="el-icon-delete"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <el-form-item size="large" class="mt-20">
        <el-button type="primary" @click="submitForm">{{$t('提交')}}</el-button>
        <el-button @click="resetForm">{{$t('重置')}}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { createSupplier, updateSupplier, getSupplier} from "@/api/ecw/supplier";
import upload from '@/components/ImageUpload'
import { getListTree } from "@/api/ecw/region";
import AreaSelector from '@/components/AreaSelector'
import {getCurrencyList} from '@/api/ecw/currency'
import Selector from '@/components/Selector'
import {validatePwd} from '@/api/ecw/busiPwd'
export default {
  components: {upload,  AreaSelector, Selector},
  props: [],
  data() {
    return {
      formData: {
        companyZh: undefined,
        agentName: undefined,
        tell: "",
        address: "",
        remark: undefined,
        field110: undefined,
        companyTypeArr: [],
        cooperationType: undefined,
        license: null,
        contract: null,
        licenseNumber: undefined,
        contactList:[],
        bankList: []
      },
      rules: {
        companyZh: [{
          required: true,
          message: this.$t('请输入公司全称'),
          trigger: 'blur'
        }],
        agentName: [],
        tell: [],
        address: [],
        remark: [],
        companyType: [{
          required: true,
          type: 'string',
          message: this.$t('请至少选择一个供应商类别'),
          trigger: 'change'
        }],
        cooperationType: [{
          required: true,
          message: this.$t('请选择合作类型'),
          trigger: 'change'
        }],
        licenseNumber: [],
      },
      treeList:[],
      provinceList:[],
      cityList:[],
      currencyList:[]
    }
  },
  computed: {
    
  },
  watch: {
      'formData.country'(country){
          this.treeList.forEach(item => {
              if(item.id == country){
                  this.provinceList = item.children || []
              }
          })
      },
      'formData.province'(province){
          this.provinceList.forEach(item => {
              if(item.id == province){
                  this.cityList = item.children || []
              }
          })
      },
      'formData.companyTypeArr'(val){
        this.$set(this.formData, 'companyType', val.join(","))
      }
  },
  created() {
      getCurrencyList().then(res => {
        this.currencyList = res.data
      })

      // 回显数据需要在加载了地区数据之后，否则无法正常回显
      getListTree({treeType: 1}).then(response => {
        this.treeList = response.data

        if(this.$route.query.id){
            getSupplier(this.$route.query.id).then(response => {
                /* response.data.companyType = response.data.companyType.split(",") || [] */
                this.formData = response.data;
            });
        }
      })
      
  },
  mounted() {},
  methods: {
    delContact(index){
      this.$confirm(this.$t('确定删除此联系人么？')).then(() => {
        this.formData.contactList.splice(index, 1)
      })
    },
    delBank(index){
      if(this.formData.bankList[index].id){
        this.$prompt(this.$t("请输入密码"), {
          inputType: 'password'
        })
        .then(({value}) => {
          if(value && value != ''){
            return validatePwd({
              busiType: 5,
              pwd: value
            })
          }
          this.$message.error(this.$t('密码不能为空'))
        })
        .then(res => {
          if(!res.data){
            return this.$message.error(this.$t('密码错误'))
          }
          this.formData.bankList.splice(index, 1)
        })
        return
      }

      this.$confirm(this.$t('确定删除此银行信息么？')).then(() => {
        this.formData.bankList.splice(index, 1)
      })
    },
    onAreaChange(type, val){
      this.$set(this.formData, type, val)
    },
    submitForm() {
      this.$refs["elForm"].validate((valid, errors) => {
        if (!valid) {
          return this.$showFormValidateErrors(errors)
        }
        if(!this.formData.bankList.length){
          return this.$message.error('请添加银行信息')
        }
        if(!this.formData.contactList.length){
          return this.$message.error('请添加联系人信息')
        }
        
        let data = Object.assign({}, this.formData)
        
        // 修改的提交
        if (data.id != null) {
          updateSupplier(data).then(response => {
            this.$modal.msgSuccess(this.$t("修改成功"));
            this.open = false;
            this.$router.back()
          });
          return;
        }
        // 添加的提交
        createSupplier(data).then(response => {
          this.$modal.msgSuccess(this.$t(this.$t("新增成功")));
          this.$redirect('supplier')
        });
      });
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
    }
  }
}

</script>
<style lang="scss" scoped>
.el-upload__tip {
  line-height: 1.2;
}
.card-header{
  display: flex;
  align-items: center;
  justify-content: space-between;
  .title{
    font-size: 18px;
  }
}
::v-deep .data-list .el-form-item__error{
    position: static;
}
.red{
  color: red;
}
</style>
