<template>
  <div>
    <div style="padding: 10px 20px 10px 20px;border-bottom: 1px solid #dadada;">
      <el-page-header
        @back="onCancel"
        :content="payType == 'create' ? '创建账号' : '修改账号'"
      ></el-page-header>
    </div>
    <div class="formContainer">
      <el-form
        :model="form"
        ref="accountForm"
        label-position="right"
        label-width="180px"
      >
        <el-form-item
          label="分部"
          prop="organId"
          :rules="[
            { required: true, message: '请选择分部', trigger: 'change' }
          ]"
        >
          <el-select
            class="multiple"
            style="width: 180px !important"
            v-model.trim="form.organId"
            filterable
            clearable
            placeholder="请选择分部"
          >
            <el-option
              v-for="(item, index) in organList"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-card>
          <el-alert
            title="企业信息"
            :closable="false"
            type="warning"
          ></el-alert>
          <el-form-item
            label="公司名称"
            prop="name"
            :rules="[
              { required: true, message: '请输入公司名称', trigger: 'blur' }
            ]"
          >
            <el-input
              v-model="form.name"
              placeholder="请输入公司名称"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="统一社会信用码"
            prop="socialCreditCode"
            :rules="[
              {
                required: true,
                message: '请输入统一社会信用码',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              v-model="form.socialCreditCode"
              placeholder="请输入统一社会信用码"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="商户证件照片"
            prop="licenceUrl"
            :rules="[
              {
                required: true,
                message: '请上传商户证件照片',
                trigger: 'change'
              }
            ]"
          >
            <el-upload
              class="avatar-upload"
              ref="upload"
              :action="ossUploadUrl"
              :on-change="$event => handleChange($event, 'licenceUrl')"
              :on-remove="() => handleRemove('licenceUrl')"
              accept="image/*"
              :multiple="false"
              :limit="1"
              :auto-upload="false"
            >
              <el-button slot="trigger" type="primary" size="small"
                >选择文件</el-button
              >
              <div
                style="display: inline; padding-left: 20px"
                class="el-upload__tip"
              >
                请上传商户证件照片。 最大限制为 9 M。
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="开户许可证照片"
            prop="openAccountLicenceUrl"
            :rules="[
              {
                required: true,
                message: '请上传开户许可证照片',
                trigger: 'change'
              }
            ]"
          >
            <el-upload
              class="avatar-upload"
              ref="upload"
              :action="ossUploadUrl"
              :on-remove="() => handleRemove('openAccountLicenceUrl')"
              :on-change="
                $event => handleChange($event, 'openAccountLicenceUrl')
              "
              accept="image/*"
              :multiple="false"
              :limit="1"
              :auto-upload="false"
            >
              <el-button slot="trigger" type="primary" size="small"
                >选择文件</el-button
              >
              <div
                style="display: inline; padding-left: 20px"
                class="el-upload__tip"
              >
                请上传开户许可证照片。 最大限制为 9 M。
              </div>
            </el-upload>
          </el-form-item>

          <el-form-item
            label="省市区"
            required
            prop="provCode"
            :rules="[
              {
                required: true,
                message: '请选择省市区',
                trigger: 'change'
              }
            ]"
          >
            <el-cascader
              placeholder="请选择省市区"
              style="width: 100%"
              :options="cityOptions"
              @change="changeCity"
            ></el-cascader>
          </el-form-item>

          <el-form-item
            label="详细地址"
            prop="address"
            :rules="[
              {
                required: true,
                message: '请选择省市区',
                trigger: 'blur'
              }
            ]"
          >
            <el-input v-model="form.address" placeholder="详细地址"></el-input>
          </el-form-item>
        </el-card>

        <el-card>
          <el-alert title="法人设置" :closable="false" type="warning">
          </el-alert>
          <el-form-item
            label="公司法人"
            prop="legalPerson"
            :rules="[
              {
                required: true,
                message: '请输入公司法人',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              v-model="form.legalPerson"
              placeholder="请输入公司法人"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="公司法人手机号"
            prop="legalMp"
            :rules="[
              {
                required: true,
                message: '请输入公司法人手机号',
                trigger: 'blur'
              },
              {
                pattern: /^1[2-9][0-9]\d{8}$/,
                message: '请输入正确的手机号',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              v-model="form.legalMp"
              maxlength="11"
              placeholder="请输入公司法人手机号"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="法人证件类型"
            prop="legalLicenceType"
            :rules="[
              {
                required: true,
                message: '请选择法人证件类型',
                trigger: 'change'
              }
            ]"
          >
            <el-select
              v-model="form.legalLicenceType"
              placeholder="请选择法人证件类型"
            >
              <el-option label="身份证" value="ID_CARD"></el-option>
              <el-option label="护照" value="PASSPORT"></el-option>
              <el-option
                label="港澳居民往来内地通行证"
                value="HM_VISITORPASS"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="法人身份证号"
            prop="legalCertId"
            :rules="[
              {
                required: true,
                message: '请输入法人身份证号',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              v-model="form.legalCertId"
              placeholder="请输入法人身份证号"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="法人证件人像面照片"
            prop="legalLicenceFrontUrl"
            :rules="[
              {
                required: true,
                message: '请上传法人证件人像面照片',
                trigger: 'change'
              }
            ]"
          >
            <el-upload
              class="avatar-upload"
              ref="upload"
              :action="ossUploadUrl"
              :on-change="
                $event => handleChange($event, 'legalLicenceFrontUrl')
              "
              :on-remove="() => handleRemove('legalLicenceFrontUrl')"
              accept="image/*"
              :multiple="false"
              :limit="1"
              :auto-upload="false"
            >
              <el-button slot="trigger" type="primary" size="small"
                >选取文件</el-button
              >
              <div
                style="display: inline; padding-left: 20px"
                class="el-upload__tip"
              >
                请上传法人证件人像面照片。 最大限制为9 M。
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="法人证件非人像面照片"
            prop="legalLicenceBackUrl"
            :rules="[
              {
                required: true,
                message: '请上传法人证件非人像面照片',
                trigger: 'change'
              }
            ]"
          >
            <el-upload
              class="avatar-upload"
              ref="upload"
              :action="ossUploadUrl"
              :on-change="$event => handleChange($event, 'legalLicenceBackUrl')"
              :on-remove="() => handleRemove('legalLicenceBackUrl')"
              accept="image/*"
              :multiple="false"
              :limit="1"
              :auto-upload="false"
            >
              <el-button slot="trigger" type="primary" size="small"
                >选取文件</el-button
              >
              <div
                style="display: inline; padding-left: 20px"
                class="el-upload__tip"
              >
                请上传法人证件非人像面照片。 最大限制为9 M。
              </div>
            </el-upload>
          </el-form-item>
        </el-card>

        <el-card>
          <el-alert title="联系人设置" :closable="false" type="warning">
          </el-alert>
          <el-form-item
            label="联系人姓名"
            prop="contactName"
            :rules="[
              {
                required: true,
                message: '请输入联系人姓名',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              v-model="form.contactName"
              placeholder="请输入联系人姓名"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="联系人证件号码"
            prop="contactLicenseNo"
            :rules="[
              {
                required: true,
                message: '请输入联系人证件号码',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              v-model="form.contactLicenseNo"
              placeholder="请输入联系人证件号码"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="联系人手机号码"
            prop="contactMobile"
            :rules="[
              {
                required: true,
                message: '请输入联系人手机号码',
                trigger: 'blur'
              },
              {
                pattern: /^1[2-9][0-9]\d{8}$/,
                message: '请输入正确的手机号',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              v-model="form.contactMobile"
              placeholder="请输入联系人手机号码"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="联系人邮箱"
            prop="contactEmail"
            :rules="[
              {
                required: true,
                message: '请输入联系人邮箱',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              v-model="form.contactEmail"
              placeholder="请输入联系人邮箱"
            ></el-input>
          </el-form-item>
        </el-card>
        <el-card>
          <el-alert title="账户设置" :closable="false" type="warning">
          </el-alert>
          <el-form-item
            label="银行卡号"
            prop="cardNo"
            :rules="[
              {
                required: true,
                message: '请输入银行卡号',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              v-model="form.cardNo"
              placeholder="请输入银行卡号"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="所属银行"
            prop="bankCode"
            :rules="[
              {
                required: true,
                message: '请选择所属银行',
                trigger: 'change'
              }
            ]"
          >
            <el-select
              v-model="form.bankCode"
              placeholder="请选择所属银行"
              filterable
            >
              <el-option
                v-for="(item, index) in backList"
                :key="index"
                :label="item.title"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="银行账户类型"
            prop="bankAcctType"
            :rules="[
              {
                required: true,
                message: '请选择银行账户类型',
                trigger: 'change'
              }
            ]"
          >
            <el-select
              v-model="form.bankAcctType"
              placeholder="请选择银行账户类型"
            >
              <el-option
                label="单位结算卡"
                value="UNIT_SETTLEMENT_CARD"
              ></el-option>
              <el-option
                label="对公账户"
                value="ENTERPRISE_ACCOUNT"
              ></el-option>
              <el-option label="借记卡" value="DEBIT_CARD"></el-option>
              <el-option label="存折" value="PASSBOOK"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="onSubmit('accountForm')"
              >确 定</el-button
            >
            <el-button @click="onCancel">取 消</el-button>
          </el-form-item>
        </el-card>
      </el-form>
    </div>
  </div>
</template>

<script>
import { yizhifuJson, cityJson } from "../../utils/cityJson";
import { yiBankJson } from "../../utils/bankJson";
import { yeepayUpload, addSubMerchant, updateMember } from "./api.js";
import { getToken, getTenantId } from "@/utils/auth";
import { policy } from "@/api/appTenant";
import { getEmployeeOrgan } from "@/api/buildTeam";
export default {
  name: "AYePayAccount",
  props: {
    row: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      payType: "create",
      backList: yiBankJson,
      cityList: cityJson,
      cityOptions: yizhifuJson,
      selectListCity: [],
      organList: [],
      headers: {
        Authorization: getToken()
      },
      fileList: [],
      files: null, // 上传对象
      id: null, // 编号
      form: {
        memberId: null,
        organId: null, // 分部
        name: null, // 公司名称
        socialCreditCode: null, // 统一社会信用码
        licenceUrl: null, // 商户证件照
        openAccountLicenceUrl: null, // 开户许可证照片
        legalPerson: null, // 公司法人
        legalMp: null, // 公司法人手机号
        legalLicenceType: null, // 法人证件类型
        legalCertId: null, // 法人身份证号
        legalLicenceFrontUrl: null, // 法人证件人像面照片
        legalLicenceBackUrl: null, // 法人证件非人像面照片
        address: null, // 详细地址

        contactName: null, // 联系人姓名
        contactLicenseNo: null, // 联系人证件号码
        contactMobile: null, // 联系人手机号码
        contactEmail: null, // 联系人邮箱

        cardNo: null, // 银行卡号
        bankCode: null, // 所属银行
        bankAcctType: null, // 银行账户类型

        provCode: null, // 省份
        areaCode: null, // 城市
        districtCode: null // 区县
      },
      ossUploadUrl: `/api-web/yeepay/upload`,
      dataObj: {
        multipartFile: ""
      }
    };
  },
  mounted() {
    console.log(this.row);
    this.__init();
    getEmployeeOrgan().then(res => {
      if (res.code == 200) {
        this.organList = res.data;
      }
    });
  },
  methods: {
    __init() {
      // this.payType = query.type;
      if (this.payType == "update") {
        const row = this.row;
        this.id = row.id;
        this.form = {
          organId: row.organId,
          memberId: row.memberId,
          name: row.name,
          legalPerson: row.legalPerson,
          legalMp: row.legalMp,
          legalCertId: row.legalCertId,
          cardNo: row.cardNo,
          bankCode: row.bankCode,
          provCode: row.provCode,
          areaCode: row.areaCode,
          socialCreditCode: row.socialCreditCode,
          address: row.address,
          bankAcctType: row.bankAcctType
        };
        // this.cityList.forEach(item => {
        //   if (item.value == row.provCode) {
        //     this.selectListCity = item.cities;
        //   }
        // });
      } else if (this.payType == "create") {
        this.$refs["accountForm"].resetFields();
      }
    },
    async onSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const form = this.form;
          let formData = new FormData();
          Object.entries(form).forEach(item => {
            formData.append(item[0], item[1]);
          });
          if (this.payType == "create") {
            addSubMerchant(formData).then(res => {
              if (res.code == 200) {
                this.$message.success("保存成功");
                this.onCancel();
              } else {
                this.$message.error(res.msg);
              }
            });
          }
          //  else if (this.payType == "update") {
          //   formData.append("id", this.id);
          //   updateMember(formData).then(res => {
          //     if (res.code == 200) {
          //       this.$message.success("保存成功");
          //       this.onCancel();
          //     } else {
          //       this.$message.error(res.msg);
          //     }
          //   });
          // }
        } else {
          this.$nextTick(() => {
            let isError = document.getElementsByClassName("is-error");
            isError[0].scrollIntoView({
              block: "center",
              behavior: "smooth"
            });
          });
          return false;
        }
      });
    },
    successed(response, file, fileList) {
      this.uploading = false;
      let url = this.ossUploadUrl + "/" + file.raw.key;
      if (url) {
        this.uploaded.push({
          url,
          name: file.name.split(".").shift(),
          clientShow: "YES"
        });
      } else {
        this.$message.error(res.data?.message || res.msg || "上传失败");
      }
      console.log(response, file, fileList);
    },
    async handleChange(file, form_key) {
      console.log("🚀 ~ file, key:", file, form_key);
      const isLt2M = file.size / 1024 / 1024 < 9;
      if (!isLt2M) {
        this.$message.error(`上传文件大小不能超过 ${9}MB!`);
        this.fileList = [];
        return;
      }
      console.log("🚀 ~ file:", file);
      let formData = new FormData();
      formData.append("multipartFile", file.raw);
      const res = await yeepayUpload(formData);
      console.log("🚀 ~ res:", res, form_key);
      if (res.data) {
        this.$message.success(`上传成功`);
      } else {
        this.$message.error(`上传失败`);
      }
      this.form[form_key] = res.data;
      this.$refs["accountForm"].validateField(form_key);

      return true;
    },
    handleRemove(form_key) {
      this.form[form_key] = null;
    },
    onCancel() {
      this.files = null;
      this.fileList = [];
      this.$emit("close");
    },
    /** 省市区改变 */
    changeCity(value) {
      console.log(value);
      this.form.provCode = value[0];
      this.form.areaCode = value[1];
      this.form.districtCode = value[2];
    }
  }
};
</script>
<style lang="scss" scoped>
.el-input,
.el-textarea,
.el-select {
  width: 100% !important;
}
.el-button--primary {
  color: #fff;
  &:hover,
  &:active,
  &:focus {
    color: #fff;
  }
}
.formContainer {
  min-width: 600px;
  height: calc(100vh - 45px);
  overflow-y: auto;
  padding: 10px;
  .el-alert,
  .el-card {
    margin-bottom: 20px;
  }
}
</style>
