<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="22">
            <span>收货地址信息列表</span>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Add" @click="handleAdd" v-hasPermi="['customer:shippingAddress:add']">添加地址</el-button>
          </el-col>
        </el-row>
      </template>
      <el-table v-loading="loading" border :data="shippingAddressList" @selection-change="handleSelectionChange">
        <el-table-column label="收货地址编号" align="center" prop="shippingAddressNo" />
        <el-table-column label="收货人" align="center" prop="consignee" />
        <el-table-column label="部门名称" align="center" prop="deptName" />
        <el-table-column label="手机号码" align="center" prop="phone" />
        <el-table-column label="详细地址" align="center" prop="address" />
        <el-table-column label="默认地址" align="center" prop="defaultAddress">
          <template #default="scope">
            <el-switch
              v-model="scope.row.defaultAddress"
              active-value="0"
              inactive-value="1"
              @change="handleDefaultAddressChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['customer:shippingAddress:edit']"
              >编辑</el-button
            >
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['customer:shippingAddress:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改客户收货地址对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="650px" append-to-body>
      <el-form ref="shippingAddressFormRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="收货人" prop="consignee">
          <el-input v-model="form.consignee" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="部门名称" prop="deptName">
          <el-input v-model="form.deptName" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="邮政编码" prop="postal">
          <el-input v-model="form.postal" placeholder="请输入邮政编码" />
        </el-form-item>
        <el-form-item label="详细地址" prop="provincialCityCountry">
          <el-cascader v-model="codeArr" :options="regionData" placeholder="请选择" @change="handleChange" style="width: 100%"></el-cascader>
        </el-form-item>
        <el-form-item prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ShippingAddress" lang="ts">
import {
  listShippingAddress,
  getShippingAddress,
  delShippingAddress,
  addShippingAddress,
  changeDefaultAddress,
  updateShippingAddress
} from '@/api/customer/customerFile/shippingAddress';
import { ShippingAddressVO, ShippingAddressQuery, ShippingAddressForm } from '@/api/customer/customerFile/shippingAddress/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import { regionData } from 'element-china-area-data';

// 接收父组件传递的props
const props = defineProps<{
  customerId?: string;
  customerNo?: string;
}>();

const shippingAddressList = ref<ShippingAddressVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const codeArr = ref([]);
const queryFormRef = ref<ElFormInstance>();
const shippingAddressFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ShippingAddressForm = {
  id: undefined,
  customerId: undefined,
  shippingAddressNo: undefined,
  consignee: undefined,
  deptId: undefined,
  phone: undefined,
  address: undefined,
  postal: undefined,
  defaultAddress: undefined,
  addressLabel: undefined,
  provincialNo: undefined,
  cityNo: undefined,
  countryNo: undefined,
  provincialCityCountry: undefined,
  pushStatus: undefined,
  num: undefined,
  deptName: undefined,
  status: undefined,
  remark: undefined
};
const data = reactive<PageData<ShippingAddressForm, ShippingAddressQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerId: undefined,
    shippingAddressNo: undefined,
    consignee: undefined,
    deptId: undefined,
    phone: undefined,
    address: undefined,
    postal: undefined,
    defaultAddress: undefined,
    addressLabel: undefined,
    provincialNo: undefined,
    cityNo: undefined,
    countryNo: undefined,
    provincialCityCountry: undefined,
    pushStatus: undefined,
    num: undefined,
    deptName: undefined,
    status: undefined,
    platformCode: undefined,
    params: {}
  },
  rules: {
    consignee: [{ required: true, message: '收货人姓名不能为空', trigger: 'blur' }],
    phone: [
      { required: true, message: '收货人手机号不能为空', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    provincialCityCountry: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 处理区域选择变化 */
const handleChange = (val: string[]) => {
  // 保存编码
  form.value.provincialNo = val[0];
  form.value.cityNo = val[1];
  form.value.countryNo = val[2];

  // 根据编码获取名称
  const names: string[] = [];
  if (val[0]) {
    const province = regionData.find((item: any) => item.value === val[0]);
    if (province) {
      names.push(province.label);

      if (val[1] && province.children) {
        const city = province.children.find((item: any) => item.value === val[1]);
        if (city) {
          names.push(city.label);

          if (val[2] && city.children) {
            const county = city.children.find((item: any) => item.value === val[2]);
            if (county) {
              names.push(county.label);
            }
          }
        }
      }
    }
  }

  // 将省市区名称用斜杠连接
  form.value.provincialCityCountry = names.join('/');
};

/** 查询客户收货地址列表 */
const getList = async () => {
  loading.value = true;
  // 使用props传递的customerId进行查询
  if (props.customerId) {
    queryParams.value.customerId = props.customerId;
  }
  const res = await listShippingAddress(queryParams.value);
  shippingAddressList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 状态修改  */
const handleDefaultAddressChange = async (row: ShippingAddressVO) => {
  //   const text = row.status === '0' ? '是' : '否';
  try {
    // await proxy?.$modal.confirm('确认要"' + text + '"吗?');
    await changeDefaultAddress(row.id, row.defaultAddress);
    proxy?.$modal.msgSuccess('操作成功');
  } catch (err) {
    row.status = row.status === '0' ? '1' : '0';
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  shippingAddressFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ShippingAddressVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  // 将props中的customerId赋值给form
  if (props.customerId) {
    form.value.customerId = props.customerId;
  }
  dialog.visible = true;
  dialog.title = '添加客户收货地址';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ShippingAddressVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getShippingAddress(_id);
  Object.assign(form.value, res.data);
  codeArr.value = [res.data.provincialNo, res.data.cityNo, res.data.countryNo];
  dialog.visible = true;
  dialog.title = '修改客户收货地址';
};

/** 提交按钮 */
const submitForm = () => {
  shippingAddressFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateShippingAddress(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addShippingAddress(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ShippingAddressVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除客户收货地址编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delShippingAddress(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'customer/shippingAddress/export',
    {
      ...queryParams.value
    },
    `shippingAddress_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  // 初始化时将customerId赋值给queryParams
  if (props.customerId) {
    queryParams.value.customerId = props.customerId;
  }
  getList();
});

// 监听props变化
watch(
  () => props.customerId,
  (newId) => {
    if (newId) {
      queryParams.value.customerId = newId;
      getList();
    }
  }
);
</script>
