<template>
  <div class="container row justify-center">
    <n-form
      :model="form"
      :rules="state.rules"
      ref="formRef"
      label-placement="left"
      label-width="100px"
      label-align="left"
      v-nloading="loading"
      :show-require-mark="false"
    >
      <n-form-item label="地区属性" path="regionType">
        <template #label>
          <span class="label-required">地区属性</span>
        </template>
        <n-radio-group
          v-model:value="form.regionType"
          @update:value="handleAreaChange"
        >
          <n-radio :value="1">中国大陆</n-radio>
          <n-radio :value="2">中国非大陆（含港澳台等地区） </n-radio>
        </n-radio-group>
      </n-form-item>

      <n-form-item label="开户行" path="bankName">
        <template #label>
          <span class="label-required">开户行</span>
        </template>
        <n-select
          v-if="form.editStatus !== 3 && form.regionType === 1"
          v-model:value="form.bankName"
          :options="bankOptions"
          placeholder="请选择开户行"
          filterable
          clearable
          @clear="handleClear"
          @update:value="handleBankChange"
        />
        <n-input
          v-else-if="form.editStatus !== 3"
          v-model:value="form.bankName"
          placeholder="请输入开户行"
          clearable
        />
        <span v-else>{{ form.bankName }}</span>
      </n-form-item>

      <n-form-item path="city">
        <template #label>
          <span class="label-required">支行</span>
        </template>
        <n-select
          class="mr-3"
          v-if="form.editStatus !== 3 && form.regionType === 1"
          v-model:value="form.province"
          :options="provinceOptions"
          placeholder="请选择省份"
          filterable
          clearable
          @clear="handleClearProvince"
          @update:value="handleProvinceChange"
        />
        <n-input
          v-else-if="form.editStatus !== 3"
          v-model:value="form.province"
          placeholder="请输入省份"
          clearable
        />
        <span v-else>{{ form.province }}</span>
        <n-select
          v-if="form.editStatus !== 3 && form.regionType === 1"
          v-model:value="form.city"
          :options="cityOptions"
          filterable
          clearable
          placeholder="请选择城市"
          @clear="handleClearCity"
          @update:value="handleCityChange"
        />
        <n-input
          v-else-if="form.editStatus !== 3"
          v-model:value="form.city"
          placeholder="请输入城市"
          clearable
        />
        <span v-else>{{ form.city }}</span>
      </n-form-item>

      <n-form-item label="&nbsp;" path="lBankName">
        <n-select
          v-if="form.editStatus !== 3 && form.regionType === 1"
          v-model:value="form.lBankName"
          :options="branchOptions"
          filterable
          @update:value="updateValue"
          clearable
          placeholder="请选择支行"
          @clear="handleClearLBankName"
          @search="handleSearch"
        />
        <n-input
          v-else-if="form.editStatus !== 3"
          v-model:value="form.lBankName"
          placeholder="请输入支行"
          clearable
        />
        <span v-else>{{ form.lBankName }}</span>
      </n-form-item>
      <n-form-item label="联行号" path="bankCode">
        <template #label>
          <span class="label-required">联行号</span>
        </template>
        <n-input
          clearable
          v-if="form.editStatus !== 3"
          v-model:value="form.bankCode"
          placeholder="请输入内容"
        />
        <span v-else>{{ form.bankCode }}</span>
      </n-form-item>

      <n-form-item label="开户行账号" path="bankNum">
        <template #label>
          <span class="label-required">开户行账号</span>
        </template>
        <n-input
          clearable
          v-if="form.editStatus !== 3"
          v-model:value="form.bankNum"
          placeholder="请输入内容"
        />
        <span v-else>{{ form.bankNum }}</span>
      </n-form-item>
      <n-form-item label="银行卡正面：" path="bankFrontImg">
        <fln-form-item
          type="upload"
          title="图片上传"
          :config="{
            limit4096: true,
            field: 'bankFrontImg',
            placeholder: '请输入银行卡正面',
            width: '120px',
          }"
          :val="form.bankFrontImg"
          :otherParams="{
            source: 'artwork',
            mask: '',
            type: 'image',
          }"
          @triggerUploadLoading="handleUploadLoading"
          @triggerValChange="handleValChange"
        />
      </n-form-item>
      <n-form-item label="银行卡背面：" path="bankBackImg">
        <fln-form-item
          type="upload"
          title="图片上传"
          :config="{
            limit4096: true,
            field: 'bankBackImg',
            placeholder: '请输入银行卡背面',
            width: '120px',
          }"
          :val="form.bankBackImg"
          :otherParams="{
            source: 'artwork',
            mask: '',
            type: 'image',
          }"
          @triggerUploadLoading="handleUploadLoading"
          @triggerValChange="handleValChange"
        />
      </n-form-item>
    </n-form>

    <div
      v-if="form.editStatus !== 3"
      class="absolute bottom-[20px] left-1/2 -translate-x-1/2"
    >
      <n-button class="w-[160px] h-[36px]" type="primary" @click="handleClick">
        保存
      </n-button>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, defineProps, watch } from "vue";
import { processError, processSuccess } from "@/utils/helper/message";
import {
  getBankInfoList,
  updateBankInfoList,
  getProvinceOptions,
  getBankOptions,
  getBranchOptions,
} from "@/api/personManage.js";
import flnFormItem from "@/components/flnlayout/form/flnformItem.vue";
import { NImage, NButton, NInput, useMessage, dialogDark } from "naive-ui";
const message = useMessage();
const props = defineProps({
  artistUid: {
    type: String,
    required: true,
  },
});

const form = reactive({
  province: "",
  city: "",
  bankName: "",
  lBankName: "",
  bankNum: "",
  editStatus: 0,
  bankFrontImg: "",
  bankBackImg: "",
  regionType: 1,
});

const state = reactive({
  rules: {
    province: [{ required: true, message: "请选择省份", trigger: "blur" }],
    city: [{ required: true, message: "请选择城市", trigger: "blur" }],
    bankName: [{ required: true, message: "请选择开户行", trigger: "blur" }],
    lBankName: [{ required: true, message: "请选择支行", trigger: "blur" }],
    bankNum: [{ required: true, message: "请输入开户行账号", trigger: "blur" }],
    bankCode: [{ required: true, message: "请输入联行号", trigger: "blur" }],
  },
  uploadField: {},
});

const formRef = ref(null);
const handleAreaChange = (value) => {
  form.province = null;
  form.city = null;
  form.bankName = null;
  form.lBankName = null;
  form.bankNum = null;
  form.bankCode = null;
  form.bankFrontImg = null;
  form.bankBackImg = null;
};
const calcRules = () => {
  if (form.regionType === 1) {
    state.rules = {
      province: [{ required: true, message: "请选择省份", trigger: "blur" }],
      city: [{ required: true, message: "请选择城市", trigger: "blur" }],
      bankName: [{ required: true, message: "请选择开户行", trigger: "blur" }],
      lBankName: [{ required: true, message: "请选择支行", trigger: "blur" }],
      bankNum: [
        { required: true, message: "请输入开户行账号", trigger: "blur" },
      ],
      bankCode: [{ required: true, message: "请输入联行号", trigger: "blur" }],
    };
    formRef.value?.restoreValidation();
  } else {
    state.rules = {
      province: [{ required: true, message: "请输入省", trigger: "blur" }],
      city: [{ required: true, message: "请输入市", trigger: "blur" }],
      bankName: [{ required: true, message: "请输入开户行", trigger: "blur" }],
      lBankName: [{ required: true, message: "请输入支行", trigger: "blur" }],
      bankNum: [
        { required: true, message: "请输入开户行账号", trigger: "blur" },
      ],
      bankCode: [{ required: true, message: "请输入联行号", trigger: "blur" }],
    };
    formRef.value?.restoreValidation();
  }
};
watch(
  () => form.regionType,
  () => {
    calcRules();
  }
);
const loading = ref(true);
const provinceOptions = ref([]);
const cityOptions = ref([]);
const bankOptions = ref([]);
const branchOptions = ref([]);
const treeOptions = ref([]);

const loadData = async (artistUid) => {
  try {
    const [bankInfoRes, provinceRes, bankRes] = await Promise.all([
      getBankInfoList({ artistUid }),
      getProvinceOptions({}),
      getBankOptions({}),
    ]);

    const bankInfo = bankInfoRes.data;
    form.province = bankInfo.bankArea[0];
    form.city = bankInfo.bankArea[1];
    form.bankName = bankInfo.bankName;
    form.lBankName = bankInfo.lBankName;
    form.bankNum = bankInfo.bankNum;
    form.bankCode = bankInfo.bankCode;
    form.editStatus = 2;
    form.bankFrontImg = bankInfo.bankFrontImg;
    form.bankBackImg = bankInfo.bankBackImg;
    form.regionType = bankInfo.regionType;

    treeOptions.value = provinceRes.data;
    provinceOptions.value = provinceRes.data.map((item) => ({
      label: item.name,
      value: item.name,
    }));

    bankOptions.value = bankRes.data.Data.map((item) => ({
      label: item,
      value: item,
    }));
    if (form.province && form.city) loadBranchInit();
    loading.value = false;
  } catch (e) {
    /*    processError(e.message || "获取数据失败");*/
    loading.value = false;
  }
};

const loadBranchOptions = async () => {
  const params = {
    province: form.province,
    city: form.city,
    bankName: form.bankName,
    lBankName: form.lBankName,
  };
  const res = await getBranchOptions(params);
  if (res?.msg === "unexpected end of JSON input") {
    return;
  }
  if (res?.data?.Data) {
    branchOptions.value = res.data.Data.map((item) => ({
      label: item.lName,
      value: item.bankCode,
    }));
  } else {
    message.error(res.msg);
  }
};
watch(
  () => {
    return form.bankCode;
  },
  () => {
    console.log("watchform.bankCode", form.bankCode);
  }
);
const updateValue = (data) => {
  form.lBankName = branchOptions.value.find(
    (item) => item.value === data
  )?.label;

  form.bankCode = data;
  console.log(form.bankCode, "form.bankCode");
  loadBranchOptions();
};
const loadBranchInit = async () => {
  try {
    const params = {
      province: form.province,
      city: form.city,
      bankName: form.bankName,
      lBankName: "",
    };
    const res = await getBranchOptions(params);
    if (res.data.Data) {
      branchOptions.value = res.data.Data.map((item) => ({
        label: item.lName,
        value: item.bankCode,
      }));
    } else {
      processError("暂无相关支行信息");
    }
  } catch (e) {
    /*    processError(e.message || "获取支行选项失败");*/
  }
};

const handleProvinceChange = (provinceId) => {
  if (provinceId) {
    form.city = "";
    form.lBankName = "";
    form.bankCode = "";
    cityOptions.value =
      treeOptions.value
        .find((item) => item.name === provinceId)
        ?.Children.map((child) => ({
          value: child.name,
          label: child.name,
        })) || [];
  }
};

const handleCityChange = (cityId) => {
  if (cityId) {
    form.lBankName = "";
    loadBranchOptions();
  }
};

const handleBankChange = (bankId) => {
  if (bankId) {
    form.province = "";
    form.city = "";
    form.lBankName = "";
    form.bankCode = "";
  }
};

const handleClear = () => {
  form.province = "";
  form.city = "";
  form.lBankName = "";
  form.bankCode = "";
};

const handleClearProvince = () => {
  form.city = "";
  form.lBankName = "";
  form.bankCode = "";
  cityOptions.value = [];
};

const handleClearCity = () => {
  form.lBankName = "";
  form.bankCode = "";
};
const handleClearLBankName = () => {
  form.bankCode = "";
};
watch(
  () => props.artistUid,
  (newVal) => {
    if (newVal) {
      loadData(newVal);
    }
  },
  { immediate: true }
);

const handleSearch = (value) => {
  form.lBankName = value;
  loadBranchOptions();
};

const handleClick = async () => {
  if (Object.values(state.uploadField).some((item) => item === true)) {
    processError("请等待图片上传完成");
    return;
  }
  const valid = await formRef.value.validate();
  if (valid) {
    const bankArea = [form.province, form.city];
    /*   form.lBankName = branchOptions.value.find((item) => item.value === form.bankCode)?.label;*/
    const params = {
      artistUid: props.artistUid,
      bankArea: bankArea,
      bankName: form.bankName,
      lBankName: form.lBankName,
      bankNum: form.bankNum,
      bankCode: form.bankCode,
      bankFrontImg: form.bankFrontImg,
      bankBackImg: form.bankBackImg,
      regionType: form.regionType,
    };
    try {
      const res = await updateBankInfoList(params);
      if (res.code == 200) {
        processSuccess("更新成功");
      }
    } catch (e) {
      /*   processError(e.message || "更新失败");*/
    }
  } else {
    processError("请填写完整表单");
  }
};
const handleValChange = ({ val, config }) => {
  form[config.field] = val;
};
const handleUploadLoading = (val) => {
  Object.assign(state.uploadField, val);
};
</script>

<style scoped>
.custom-title {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
}
</style>
