<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="timestamp" clearable></el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('合作结束时间')" prop="cooperationDateEnd">
          <el-date-picker v-model="formData.cooperationDateEnd" value-format="timestamp" 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="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-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 { createLadingShipper, updateLadingShipper, getLadingShipper } from "@/api/ecw/ladingShipper";
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'
import { getDockPage } from "@/api/ecw/dock";
export default {
  components: {upload,  AreaSelector, Selector},
  props: [],
  data() {
    return {
      disabled: false,
      formData: {
        areaType: 0,
        companyZh: undefined,
        agentName: undefined,
        tell: "",
        address: "",
        remark: undefined,
        field110: undefined,
        companyTypeArr: [],
        cooperationType: undefined,
        settlementPeriod: undefined,
        priceAdvantage: undefined,
        license: null,
        contract: null,
        licenseNumber: undefined,
        contactList:[],
        bankList: [],
        resourceVO: {},
        externalVO: {}
      },
      rules: {
        companyZh: [{
          required: true,
          message: this.$t('请输入公司全称'),
          trigger: 'blur'
        }],
        agentName: [],
        tell: [],
        address: [],
        remark: [],
        licenseNumber: [],
      },
      treeList:[],
      provinceList:[],
      cityList:[]
    }
  },
  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 || []
              }
          })
      }
  },
  created() {
      getCurrencyList().then(res => {
        this.currencyList = res.data
      })

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

        if(this.$route.query.id){
            getLadingShipper(this.$route.query.id).then(response => {
                this.formData = response.data
            });
        }
      })
      
  },
  mounted() {},
  methods: {
    strToArray(val) {
      if(!val || val == '') {
        return []
      }else{
        let data = val.split(",")
        return data.map(item=>Number(item))
      }
    },
    sameReceive() {
      this.$set(this.formData.externalVO,'notifyCompanyName',this.formData.externalVO.receiveCompanyName)
      this.$set(this.formData.externalVO,'notifyAddress',this.formData.externalVO.receiveAddress)
      this.$set(this.formData.externalVO,'notifyTel',this.formData.externalVO.receiveTel)
      this.$set(this.formData.externalVO,'notifyEmail',this.formData.externalVO.receiveEmail)
    },
    addFileNo() {
      this.showFileNoDialog = true
      this.$refs.fileNoForm.resetFields()
    },
    getFile() {
      getFileNoPage().then(res => {
        this.fileList = res.data.list
      })
    },
    addfile() {
      this.$refs.fileNoForm.validate(vaild=>{
        if(vaild){
          createFileNo(this.fileNoForm).then(()=>{
            this.showFileNoDialog = false
            this.getFile()
          })
        }else{
          this.$message.error(this.$t('请完整填写表单'))
        }
      })
    },
    changeFile(val) {
      let file = this.fileList.find(item=>item.id == val)
      this.$set(this.formData.externalVO,'fromNo',file.fromNo)
      this.$set(this.formData.externalVO,'baNo',file.baNo)
    },
    changeRequire(val) {
      if(val != '自定义'){
        this.$set(this.formData.externalVO,'clearanceRequire',val)
      }else{
        this.$set(this.formData.externalVO,'clearanceRequire','')
      }
    },
    getCountry(countryId, districtId) {
      let country = this.treeList.find(item=>item.id == countryId)
      let district = country.children.find(item=>item.id == districtId)
      return this.$l(country, 'title')+' '+this.$l(district, 'title')
    },
    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)
        }
        
        let data = JSON.parse(JSON.stringify(this.formData))
        // 修改的提交
        if (data.id != null) {
          updateLadingShipper(data).then(response => {
            this.$modal.msgSuccess(this.$t("修改成功"));
            this.open = false;
            this.$router.back()
          });
          return;
        }
        // 添加的提交
        createLadingShipper(data).then(response => {
          this.$modal.msgSuccess(this.$t("新增成功"));
          this.$redirect('/supplier/ladingshipper')
        });
      });
    },
    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;
}
.supplier-item{
  margin-left: 30px;
  
}
</style>
