<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { fetchCreateDetailEntry, fetchUpdateDetailEntry } from '@/service/api/mps/detail-entry';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { useDict } from '@/hooks/business/dict';import { $t } from '@/locales';

defineOptions({
  name: 'DetailEntryOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Mps.DetailEntry | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { options: mpsCustTypeOptions } = useDict('mps_cust_type');

const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增每日录入明细',
    edit: '编辑每日录入明细'
  };
  return titles[props.operateType];
});

type Model = Api.Mps.DetailEntryOperateParams;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
      subcategoryId: undefined,
      subcategoryName: '',
      yxName: '',
      jbName: '',
      yxId: '',
      jbId: '',
      date: undefined,
      deptName: '',
      deptId: undefined,
      custType: '',
      custId: '',
      custName: '',
      custAcctNo: '',
      custPhoneNo: '',
      magneticCardId: undefined,
      acquiringName: '',
      acquiringId: '',
      internetChannel: '',
      trafficId: undefined,
      workplace: '',
      surplusAccountName: '',
      heatingNo: '',
      checkFlag: '',
      checkTime: undefined,
      checkUser: '',
      checkType: '',
      checkMsg: '',
  };
}

type RuleKey = Extract<
  keyof Model,
  | 'subcategoryId'
  | 'jbName'
  | 'jbId'
  | 'date'
  | 'tenantId'
  | 'createDept'
  | 'createBy'
  | 'createTime'
  | 'updateBy'
  | 'updateTime'
  | 'delFlag'
>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  subcategoryId: createRequiredRule('业务类型id不能为空'),
  jbName: createRequiredRule('经办人员名称不能为空'),
  jbId: createRequiredRule('经办人员营销号不能为空'),
  date: createRequiredRule('数据日期不能为空'),
  tenantId: createRequiredRule('租户编号不能为空'),
  createDept: createRequiredRule('创建部门不能为空'),
  createBy: createRequiredRule('创建者不能为空'),
  createTime: createRequiredRule('创建时间不能为空'),
  updateBy: createRequiredRule('更新者不能为空'),
  updateTime: createRequiredRule('更新时间不能为空'),
  delFlag: createRequiredRule('删除标志（0代表存在 1代表删除）不能为空')
};

function handleUpdateModelWhenEdit() {
  if (props.operateType === 'add') {
    Object.assign(model, createDefaultModel());
    return;
  }

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  const { dataId, subcategoryId, subcategoryName, yxName, jbName, yxId, jbId, date, deptName, deptId, custType, custId, custName, custAcctNo, custPhoneNo, magneticCardId, acquiringName, acquiringId, internetChannel, trafficId, workplace, surplusAccountName, heatingNo, checkFlag, checkTime, checkUser, checkType, checkMsg } = model;

  // request
  if (props.operateType === 'add') {
    const { error } = await fetchCreateDetailEntry({ subcategoryId, subcategoryName, yxName, jbName, yxId, jbId, date, deptName, deptId, custType, custId, custName, custAcctNo, custPhoneNo, magneticCardId, acquiringName, acquiringId, internetChannel, trafficId, workplace, surplusAccountName, heatingNo, checkFlag, checkTime, checkUser, checkType, checkMsg });
    if (error) return;
  }

  if (props.operateType === 'edit') {
    const { error } = await fetchUpdateDetailEntry({ dataId, subcategoryId, subcategoryName, yxName, jbName, yxId, jbId, date, deptName, deptId, custType, custId, custName, custAcctNo, custPhoneNo, magneticCardId, acquiringName, acquiringId, internetChannel, trafficId, workplace, surplusAccountName, heatingNo, checkFlag, checkTime, checkUser, checkType, checkMsg });
    if (error) return;
  }

  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="800" class="max-w-90%">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="业务类型id" path="subcategoryId">
          <NInput v-model:value="model.subcategoryId" placeholder="请输入业务类型id" />
        </NFormItem>
        <NFormItem label="业务类型名称" path="subcategoryName">
          <NInput v-model:value="model.subcategoryName" placeholder="请输入业务类型名称" />
        </NFormItem>
        <NFormItem label="营销人员名称" path="yxName">
          <NInput v-model:value="model.yxName" placeholder="请输入营销人员名称" />
        </NFormItem>
        <NFormItem label="经办人员名称" path="jbName">
          <NInput v-model:value="model.jbName" placeholder="请输入经办人员名称" />
        </NFormItem>
        <NFormItem label="营销人员营销号" path="yxId">
          <NInput v-model:value="model.yxId" placeholder="请输入营销人员营销号" />
        </NFormItem>
        <NFormItem label="经办人员营销号" path="jbId">
          <NInput v-model:value="model.jbId" placeholder="请输入经办人员营销号" />
        </NFormItem>
        <NFormItem label="数据日期" path="date">
          <NDatePicker
            v-model:formatted-value="model.date"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            clearable
          />
        </NFormItem>
        <NFormItem label="部门名称" path="deptName">
          <NInput v-model:value="model.deptName" placeholder="请输入部门名称" />
        </NFormItem>
        <NFormItem label="部门id" path="deptId">
          <NInput v-model:value="model.deptId" placeholder="请输入部门id" />
        </NFormItem>
        <NFormItem label="客户类型（1-个人，2-对公）" path="custType">
          <NSelect
            v-model:value="model.custType"
            placeholder="请选择客户类型（1-个人，2-对公）"
            :options="mpsCustTypeOptions"
            clearable
          />
        </NFormItem>
        <NFormItem label="客户身份证号" path="custId">
          <NInput v-model:value="model.custId" placeholder="请输入客户身份证号" />
        </NFormItem>
        <NFormItem label="客户姓名" path="custName">
          <NInput v-model:value="model.custName" placeholder="请输入客户姓名" />
        </NFormItem>
        <NFormItem label="客户账号/卡号" path="custAcctNo">
          <NInput v-model:value="model.custAcctNo" placeholder="请输入客户账号/卡号" />
        </NFormItem>
        <NFormItem label="客户联系电话" path="custPhoneNo">
          <NInput v-model:value="model.custPhoneNo" placeholder="请输入客户联系电话" />
        </NFormItem>
        <NFormItem label="磁条卡更换登记id" path="magneticCardId">
          <NInput v-model:value="model.magneticCardId" placeholder="请输入磁条卡更换登记id" />
        </NFormItem>
        <NFormItem label="综合收单商户名" path="acquiringName">
          <NInput v-model:value="model.acquiringName" placeholder="请输入综合收单商户名" />
        </NFormItem>
        <NFormItem label="综合收单商户号" path="acquiringId">
          <NInput v-model:value="model.acquiringId" placeholder="请输入综合收单商户号" />
        </NFormItem>
        <NFormItem label="网上支付开通渠道" path="internetChannel">
          <NCheckboxGroup v-model:value="model.internetChannel">
            <NSpace>
              <NCheckbox
                v-for="option in mpsCustTypeOptions"
                :key="option.value"
                :value="option.value"
                :label="option.label"
              />
            </NSpace>
          </NCheckboxGroup>
        </NFormItem>
        <NFormItem label="交警处罚决定书" path="trafficId">
          <NInput v-model:value="model.trafficId" placeholder="请输入交警处罚决定书" />
        </NFormItem>
        <NFormItem label="职工所属单位" path="workplace">
          <NInput v-model:value="model.workplace" placeholder="请输入职工所属单位" />
        </NFormItem>
        <NFormItem label="公积金缴纳账户名称" path="surplusAccountName">
          <NInput v-model:value="model.surplusAccountName" placeholder="请输入公积金缴纳账户名称" />
        </NFormItem>
        <NFormItem label="取暖费户号" path="heatingNo">
          <NInput v-model:value="model.heatingNo" placeholder="请输入取暖费户号" />
        </NFormItem>
        <NFormItem label="核对标志（0未核对 1核对通过 9核对失败）" path="checkFlag">
          <NInput v-model:value="model.checkFlag" placeholder="请输入核对标志（0未核对 1核对通过 9核对失败）" />
        </NFormItem>
        <NFormItem label="核对时间" path="checkTime">
          <NDatePicker
            v-model:formatted-value="model.checkTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            clearable
          />
        </NFormItem>
        <NFormItem label="核对人员（人工核对时）" path="checkUser">
          <NInput v-model:value="model.checkUser" placeholder="请输入核对人员（人工核对时）" />
        </NFormItem>
        <NFormItem label="核对方式（0系统 1人工 2其他1 3其他2 4其他3）" path="checkType">
          <NInput v-model:value="model.checkType" placeholder="请输入核对方式（0系统 1人工 2其他1 3其他2 4其他3）" />
        </NFormItem>
        <NFormItem label="核对结果" path="checkMsg">
          <NInput v-model:value="model.checkMsg" placeholder="请输入核对结果" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
