<template>
  <div>
    <PlusPage
      ref="plusPageInstance"
      :columns="tableConfig"
      :request="getList"
      :is-card="true"
      :search="{
        labelWidth: 100,
        showNumber: 3
      }"
      :table="{
        actionBar: { buttons, type: 'link', width: 180 },
        adaptive: { offsetBottom: 50 },
        hasIndexColumn: true
      }"
      :pageInfoMap="{ page: 'pageNum', pageSize: 'pageSize' }"
    >
      <template #table-title>
        <el-row class="button-row">
          <el-button size="default" type="success" @click="handleCreate">
            新增
          </el-button>
        </el-row>
      </template>
    </PlusPage>
    <!-- 弹窗编辑 -->
    <PlusDialogForm
      ref="dialogForm"
      v-model="form"
      v-model:visible="dialogVisible"
      :form="{
        columns,
        labelPosition: 'left',
        labelWidth: 190,
        rules
      }"
      :dialog="{ title: dialogTitle + '菜单', width: 600, confirmLoading }"
      @confirm="handleSubmit"
      @close="handleClose"
    />
  </div>
</template>

<script lang="ts" setup>
import {
  computed,
  onMounted,
  reactive,
  ref,
  resolveDirective,
  toRefs
} from "vue";
import type { FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import {
  type FieldValues,
  type PlusColumn,
  PlusDialogForm,
  PlusPage,
  PlusPageInstance,
  useTable
} from "plus-pro-components";
import { useRouter } from "vue-router";
import {
  createChildAccount,
  getChildAccountList,
  merchantUserInfoDetail,
  merchantUserInfoupdateAllocationStatus,
  merchantUserInfoupdateStatus,
  updateChildAccount
} from "@/api/childAccount";
import { AesEncode } from "@/utils/crypto";
import { md5 } from "js-md5";

defineOptions({
  name: "ChildAccount"
});

const router = useRouter();

const plusPageInstance = ref<PlusPageInstance | null>(null);

const getList = async (query: Record<string, any>) => {
  let res = await getChildAccountList(query);
  return {
    data: res.data.list,
    total: res.data.total
  };
};

// 重新请求列表接口
const refresh = () => {
  plusPageInstance.value?.getList();
};

const dialogTitle = computed(() => (state.isCreate ? "新增" : "编辑"));

// 表格数据
const tableConfig: PlusColumn[] = [
  {
    label: "姓名",
    prop: "contractName",
    hideInSearch: true
  },
  {
    label: "手机号",
    prop: "contractMobile",
    hideInSearch: true
  },
  {
    label: "备注",
    prop: "remark",
    hideInSearch: true
  },
  {
    label: "创建人",
    prop: "creater",
    hideInSearch: true
  },
  {
    label: "创建时间",
    prop: "createTime",
    hideInSearch: true
  },
  {
    label: "微信号",
    prop: "wechat",
    hideInSearch: true
  },
  {
    label: "接单状态",
    prop: "receiveStatus",
    valueType: "select",
    options: [
      { label: "接单", value: true },
      { label: "不接单", value: false }
    ],
    hideInSearch: true
  },
  {
    label: "当前状态",
    prop: "status",
    valueType: "select",
    options: [
      { label: "正常", value: "1" },
      { label: "禁用", value: "0" }
    ],
    hideInSearch: true
  }
];

/*--------------------表单--------------------*/

// 表单实例
const dialogForm = ref(null);

interface State {
  dialogVisible: boolean;
  detailsVisible: boolean;
  confirmLoading: boolean;
  selectedIds: number[];
  isCreate: boolean;
  form: Record<string, any>;
  rules: FormRules;
}

const state = reactive<State>({
  dialogVisible: false,
  detailsVisible: false,
  confirmLoading: false,
  selectedIds: [],
  isCreate: false,
  form: {},
  rules: {
    contractName: [
      {
        required: true,
        message: "请输入姓名",
        trigger: "blur"
      }
    ],
    contractMobile: [
      {
        required: true,
        message: "请输入手机号",
        trigger: "blur"
      },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: "请输入正确的手机号",
        trigger: "blur"
      }
    ],
    accountName: [
      {
        required: true,
        message: "请输入账号",
        trigger: "blur"
      }
    ],
    contractPassword: [
      {
        pattern:
          /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,16}$/,
        message: "输入8到16位密码，须包括大小写字母、数字和特殊符号",
        trigger: "blur"
      }
    ]
  }
});

const columns: PlusColumn[] = [
  {
    label: "姓名",
    prop: "contractName",
    fieldProps: {
      clearable: true
    }
  },
  {
    label: "手机号",
    prop: "contractMobile",
    fieldProps: {
      clearable: true
    }
  },
  {
    label: "微信号",
    prop: "wechat",
    fieldProps: {
      clearable: true
    }
  },
  {
    label: "账号",
    prop: "accountName",
    fieldProps: computed(() => {
      return {
        disabled: !state.isCreate
      };
    })
  },
  {
    label: "密码",
    prop: "contractPassword",
    fieldProps: {
      type: "password",
      clearable: true,
      showPassword: true
    }
  },
  {
    label: "确认密码",
    prop: "confirmPassword",
    fieldProps: {
      type: "password",
      clearable: true,
      showPassword: true
    },
    formItemProps: computed(() => ({
      required:
        form.value.contractPassword !== "" &&
        form.value.contractPassword !== null &&
        form.value.contractPassword !== undefined,
      rules: [
        {
          required: true,
          message: "请输入确认密码",
          trigger: "blur"
        },
        {
          validator: (rule, value, callback) => {
            if (value !== form.value.contractPassword) {
              callback(new Error("密码不一致"));
            } else {
              callback();
            }
          }
        }
      ]
    }))
  },
  {
    label: "是否愿意客户主动电话联系",
    prop: "isAllowCusContact",
    valueType: "radio",
    options: [
      {
        label: "是",
        value: true
      },
      {
        label: "否",
        value: false
      }
    ]
  },
  {
    label: "备注",
    prop: "remark",
    fieldProps: {
      type: "textarea",
      rows: 4,
      clearable: true,
      maxlength: 200,
      showWordLimit: true
    }
  }
];

// 创建
const handleCreate = (): void => {
  form.value = {
    status: "normal"
  };
  state.isCreate = true;
  state.dialogVisible = true;
};

const handleSubmit = async (values: FieldValues) => {
  console.log(values, "Submit");
  confirmLoading.value = true;
  if (state.isCreate) {
    try {
      let params = form.value;
      params.contractPassword = form.value.contractPassword
        ? md5(form.value.contractPassword).toUpperCase()
        : "";
      params.confirmPassword = form.value.confirmPassword
        ? md5(form.value.confirmPassword).toUpperCase()
        : "";
      let res = await createChildAccount(params);
      if (res.code === 0) {
        ElMessage.success("新增成功");
        confirmLoading.value = false;
        dialogVisible.value = false;
        refresh();
      } else {
        ElMessage.error(res.msg);
      }
    } finally {
      confirmLoading.value = false;
    }
  } else {
    // 编辑
    try {
      let params = form.value;
      params.contractPassword = md5(form.value.contractPassword).toUpperCase();
      params.confirmPassword = md5(form.value.confirmPassword).toUpperCase();
      let res = await updateChildAccount(params);
      if (res.code === 0) {
        ElMessage.success("修改成功");
        confirmLoading.value = false;
        dialogVisible.value = false;
        refresh();
      } else {
        ElMessage.error(res.msg);
      }
    } finally {
      confirmLoading.value = false;
    }
  }
};

const handleClose = () => {
  // 重置表单校验状态
  console.log(dialogForm.value.formInstance);
};

const { buttons } = useTable();

const perms = resolveDirective("perms");

buttons.value = [
  {
    // 修改
    text: "修改",
    code: "edit",
    // props v0.1.16 版本新增函数类型
    props: {
      type: "primary"
    },
    onClick(params) {
      merchantUserInfoDetail(params.row.id).then(res => {
        if (res.code === 0) {
          let data = res.data;
          data.contractPassword = "";
          data.confirmPassword = "";
          form.value = data;
          state.isCreate = false;
          state.dialogVisible = true;
        }
      });
    }
  },
  {
    // 修改
    text: "修改状态",
    props: {
      type: "warning"
    },
    confirm: {
      options: {
        draggable: true,
        message: "确认修改状态?"
      }
    },
    onConfirm: async params => {
      try {
        let res = await merchantUserInfoupdateStatus({
          id: params.row.id,
          status: params.row.status === "1" ? "0" : "1"
        });
        if (res.code === 0) {
          ElMessage.success("修改成功");
          refresh();
        } else {
          ElMessage.error(res.msg);
        }
      } catch (e) {
        ElMessage.error("删除失败");
      }
    }
  },
  {
    // 修改
    text: "修改接单状态",
    props: {
      type: "warning"
    },
    confirm: {
      options: {
        draggable: true,
        message: "确认修改接单状态?"
      }
    },
    onConfirm: async params => {
      try {
        let res = await merchantUserInfoupdateAllocationStatus({
          ids: [params.row.id],
          allocationStatus: params.row.receiveStatus === true ? false : true
        });
        if (res.code === 0) {
          ElMessage.success("修改成功");
          refresh();
        } else {
          ElMessage.error(res.msg);
        }
      } catch (e) {
        ElMessage.error("删除失败");
      }
    }
  }
];

const { form, confirmLoading, rules, dialogVisible } = toRefs(state);
</script>
