<script lang="ts" setup>
/**
 * @Name: EditDrawer.vue
 * @Description: 店铺编辑
 * @Author: Cheney
 */

import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { useResponse } from '/@/utils/useResponse';
import * as api from '/@/views/shop-information/api';


const loading = ref(false);
const isOpen = defineModel({ default: false });

const props = defineProps<{
  gridOptions: any;
  platformNumber: string;
  formSelect: { country: string[], line: string[] };
  companySelect: any;
  operatorOption: { id: number, name: string }[]
}>();
const { gridOptions, platformNumber, formSelect, companySelect, operatorOption } = props;

const emit = defineEmits([ 'refresh' ]);

onBeforeMount(() => {
  replaceCol();
});

interface RuleForm {
  operator: string[];
  operatorName: string[];
  platformNumber: string;
  platformName: string;
  country: string;
  brandName: string;
  currencyCode: string;
  status: number;
  platform: string;
  line: string[];
  ipaddress: string;
  company: string;
  belongsCompany: string;
  companyEnglishName: string;
  address: string;
  juridicalPerson: string;
  juridicalPersonCreditCard: string;
  juridicalPersonCreditCardAddress: string;
  receivablesAccount: string;
  receivablesAccountCompany: string;
  vatNumber: string;
  vatCompany: string;
  shopPhoneAndName: string | null;
  shopEmail: string | null;
  subShopPhoneAndName: string | null;
  subShopEmail: string | null;
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  operator: [],
  operatorName: [],
  platformNumber: '',
  platformName: '',
  country: '',
  brandName: '',
  currencyCode: '',
  status: 0,
  platform: '',
  line: [],
  ipaddress: '',
  company: '',
  belongsCompany: '',
  companyEnglishName: '',
  address: '',
  juridicalPerson: '',
  juridicalPersonCreditCard: '',
  juridicalPersonCreditCardAddress: '',
  receivablesAccount: '',
  receivablesAccountCompany: '',
  vatNumber: '',
  vatCompany: '',
  shopPhoneAndName: '',
  shopEmail: '',
  subShopPhoneAndName: '',
  subShopEmail: ''
});

const rules = reactive<FormRules<RuleForm>>({
  platformNumber: [
    { required: true, message: 'Please input platform name', trigger: 'blur' }
  ],
  platformName: [
    { required: true, message: 'Please input platform name', trigger: 'blur' }
  ],
  country: [
    { required: true, message: 'Please input country name', trigger: 'blur' }
  ],
  brandName: [
    { message: 'Please input brand name', trigger: 'blur' }
  ],
  currencyCode: [
    { required: true, message: 'Please select currency code', trigger: 'change' }
  ],
  platform: [
    { required: true, message: 'Please input platform name', trigger: 'blur' }
  ],
  line: [
    { required: true, message: 'Please select line', trigger: 'change' }
  ],
  ipaddress: [
    { message: 'Please input ip address', trigger: 'blur' }
  ],
  company: [
    { message: 'Please input activity form', trigger: 'blur' }
  ],
  belongsCompany: [ { required: true, message: 'Please Select belongsCompany', trigger: 'change' } ],
  companyEnglishName: [
    { message: 'Please input Company English Name', trigger: 'blur' }
  ],
  address: [
    { message: 'Please input Address', trigger: 'blur' }
  ],
  juridicalPerson: [
    { message: 'Please input Juridical Person', trigger: 'blur' }
  ],
  juridicalPersonCreditCard: [
    { message: 'Please input Juridical Person Credit Card', trigger: 'blur' }
  ],
  juridicalPersonCreditCardAddress: [
    { message: 'Please input Juridical Person Credit Card Address', trigger: 'blur' }
  ],
  receivablesAccount: [
    { message: 'Please input Receivables Account', trigger: 'blur' }
  ],
  receivablesAccountCompany: [
    { message: 'Please input Receivables Account Company', trigger: 'blur' }
  ],
  vatNumber: [
    { message: 'Please input VAT Number', trigger: 'blur' }
  ],
  vatCompany: [
    { message: 'Please input VAT Company', trigger: 'blur' }
  ],
  shopPhoneAndName: [
    { message: 'Please input Shop Email', trigger: 'blur' }
  ],
  shopEmail: [
    { message: 'Please input Shop Email', trigger: 'blur' }
  ],
  subShopPhoneAndName: [
    { message: 'Please input Shop Email', trigger: 'blur' }
  ],
  subShopEmail: [
    { message: 'Please input Sub Shop Email', trigger: 'blur' }
  ]
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      ruleForm.operator = ruleForm.operatorName;
      await useResponse({ id: gridOptions.data[0].id, partial: 1, formData: ruleForm }, api.updateShopDetail, loading);
      isOpen.value = false;
      ElMessage.success('编辑成功');
      emit('refresh');
    } else {
      console.log('error submit!', fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

function replaceCol() {
  const result = Object.keys(ruleForm).reduce((acc, key) => {
    if (key in gridOptions.data[0]) {
      // 特殊处理 operatorName 字段
      if (key === 'operatorName') {
        const names = gridOptions.data[0][key].split(',');
        const ids = names
            .map((name: any) => {
              const operator = operatorOption.find(opt => opt.name === name.trim()); // 去除多余空格并查找
              return operator ? operator.id : null;
            })
            .filter((id: any) => id !== null); // 过滤掉未找到的id
        acc[key] = ids; // 将找到的所有id赋值给operatorName
      } else {
        acc[key] = gridOptions.data[0][key];
      }
    }
    return acc;
  }, {} as { [key: string]: any });
  Object.assign(ruleForm, result);
}
</script>

<template>
  <el-drawer v-model="isOpen" :title="`店铺编辑 - ${platformNumber}`" size="30%">
    <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        class="mx-2.5 mt-2.5"
        label-width="auto"
        status-icon>
      <el-form-item label="运营" prop="operatorName">
        <el-select v-model="ruleForm.operatorName" collapse-tags collapse-tags-tooltip multiple>
          <el-option v-for="item in operatorOption" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="平台编号" prop="platformNumber">
        <el-input v-model="ruleForm.platformNumber" />
      </el-form-item>
      <el-form-item label="平台名称" prop="platformName">
        <el-input v-model="ruleForm.platformName" />
      </el-form-item>
      <el-form-item label="国家" prop="country">
        <el-select v-model="ruleForm.country" placeholder="请选择线路">
          <el-option
              v-for="item in formSelect.country"
              :key="item"
              :label="item"
              :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="品牌名称" prop="brandName">
        <el-input v-model="ruleForm.brandName" />
      </el-form-item>
      <el-form-item label="货币代码" prop="currencyCode">
        <el-input v-model="ruleForm.currencyCode" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="ruleForm.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="平台" prop="platform">
        <el-input v-model="ruleForm.platform" />
      </el-form-item>
      <el-form-item label="线路" prop="line">
        <el-select v-model="ruleForm.line" placeholder="请选择线路">
          <el-option
              v-for="item in formSelect.line"
              :key="item"
              :label="item"
              :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="IP 地址" prop="ipaddress">
        <el-input v-model="ruleForm.ipaddress" />
      </el-form-item>
      <el-form-item label="公司" prop="company">
        <el-input v-model="ruleForm.company" />
      </el-form-item>
      <el-form-item label="关联公司" prop="belongsCompany">
        <el-select v-model="ruleForm.belongsCompany" placeholder="请选择所属公司">
          <el-option
              v-for="item in companySelect"
              :key="item.id"
              :label="item.company"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="公司英文名称" prop="companyEnglishName">
        <el-input v-model="ruleForm.companyEnglishName" />
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="ruleForm.address" />
      </el-form-item>
      <el-form-item label="法人代表" prop="juridicalPerson">
        <el-input v-model="ruleForm.juridicalPerson" />
      </el-form-item>
      <el-form-item label="法人信用卡" prop="juridicalPersonCreditCard">
        <el-input v-model="ruleForm.juridicalPersonCreditCard" />
      </el-form-item>
      <el-form-item label="法人信用卡地址" prop="juridicalPersonCreditCardAddress">
        <el-input v-model="ruleForm.juridicalPersonCreditCardAddress" />
      </el-form-item>
      <el-form-item label="应收账款账户" prop="receivablesAccount">
        <el-input v-model="ruleForm.receivablesAccount" />
      </el-form-item>
      <el-form-item label="应收账款公司" prop="receivablesAccountCompany">
        <el-input v-model="ruleForm.receivablesAccountCompany" />
      </el-form-item>
      <el-form-item label="VAT税号" prop="vatNumber">
        <el-input v-model="ruleForm.vatNumber" />
      </el-form-item>
      <el-form-item label="VAT公司" prop="vatCompany">
        <el-input v-model="ruleForm.vatCompany" />
      </el-form-item>
      <el-form-item label="主账户电话" prop="shopPhoneAndName">
        <el-input v-model="ruleForm.shopPhoneAndName" />
      </el-form-item>
      <el-form-item label="主账户邮箱" prop="shopEmail">
        <el-input v-model="ruleForm.shopEmail" />
      </el-form-item>
      <el-form-item label="子账户电话" prop="subShopPhoneAndName">
        <el-input v-model="ruleForm.subShopPhoneAndName" />
      </el-form-item>
      <el-form-item label="子账户邮箱" prop="subShopEmail">
        <el-input v-model="ruleForm.subShopEmail" />
      </el-form-item>
      <el-form-item>
        <div class="flex flex-1 justify-center">
          <el-button :loading="loading" type="primary" @click="submitForm(ruleFormRef)">确 定</el-button>
          <el-button @click="resetForm(ruleFormRef)">重 置</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style scoped>

</style>
