<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑续费订单' : '创建续费订单'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 4, sm: 5, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
      "
    >
      <a-form-item label="选择项目" name="appId">
        <a-select
          v-model:value="form.appId"
          show-search
          :filter-option="false"
          style="width: 350px"
          placeholder="选择项目"
          :options="state.data"
          @search="fetchProject"
          @change="onDone"
        >
          <template v-if="state.fetching" #notFoundContent>
            <a-spin size="small"/>
          </template>
        </a-select>
      </a-form-item>
      <a-form-item label="续费时长" name="duration">
        <a-radio-group v-model:value="form.duration" button-style="solid" @change="handleDuration" @blur="handleDuration">
          <template v-for="item in durationDict">
            <a-radio-button :value="item.value">{{ item.dictDataName }}</a-radio-button>
          </template>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="续费天数" name="days" v-if="form.duration == 0">
        <a-input-number
          allow-clear
          placeholder="请输入天数"
          style="width: 120px"
          v-model:value="form.days"
          @change="handleDays"
        />
        天
      </a-form-item>
      <a-form-item label="续费金额" name="payPrice">
        <a-input-number
          allow-clear
          placeholder="请输入续费金额"
          prefix="￥"
          suffix="元"
          :precision="2"
          style="width: 350px"
          v-model:value="form.payPrice"
        />
      </a-form-item>
      <a-form-item label="支付方式" name="payType">
        <a-radio-group v-model:value="form.payType" disabled button-style="solid" @change="handleDuration" @blur="handleDuration">
            <a-radio-button :value="0">余额支付</a-radio-button>
            <a-radio-button :value="102">微信</a-radio-button>
            <a-radio-button :value="3">支付宝</a-radio-button>
            <a-radio-button :value="4">现金</a-radio-button>
            <a-radio-button :value="402">银行转账</a-radio-button>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="付款凭证" name="images">
        <SelectFile
          :placeholder="`请上传付款凭证`"
          :limit="1"
          :data="images"
          @done="chooseImage"
          @del="onDeleteItem"
        />
      </a-form-item>
      <a-form-item label="备注" name="comments">
        <a-textarea
          :rows="4"
          :maxlength="200"
          placeholder="请输入描述"
          v-model:value="form.comments"
        />
      </a-form-item>
      <a-form-item label="财务审核" name="status" v-if="hasRole('finance')">
        <a-radio-group v-model:value="form.status">
          <a-radio :value="1">已入账</a-radio>
          <a-radio :value="0">待审核</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
import {ref, reactive, watch} from 'vue';
import {Form, message} from 'ant-design-vue';
import {assignObject, uuid} from 'ele-admin-pro';
import {addProjectRenew, updateProjectRenew} from '@/api/project/projectRenew';
import {ProjectRenew} from '@/api/project/projectRenew/model';
import {useThemeStore} from '@/store/modules/theme';
import {storeToRefs} from 'pinia';
import {debounce} from 'lodash-es';
import {formatNumber} from 'ele-admin-pro/es';
import {ItemType} from 'ele-admin-pro/es/ele-image-upload/types';
import {FormInstance} from 'ant-design-vue/es/form';
import {pageProject} from "@/api/project/project";
import {Project} from "@/api/project/project/model";
import {listDictData} from "@/api/system/dict-data";
import {DictData} from "@/api/system/dict-data/model";
import {FileRecord} from "@/api/system/file/model";
import {hasRole} from "@/utils/permission";

// 是否是修改
const isUpdate = ref(false);
const useForm = Form.useForm;
// 是否开启响应式布局
const themeStore = useThemeStore();
const {styleResponsive} = storeToRefs(themeStore);

const props = defineProps<{
  // 弹窗是否打开
  visible: boolean;
  // 修改回显的数据
  data?: ProjectRenew | null;
}>();

const emit = defineEmits<{
  (e: 'done'): void;
  (e: 'update:visible', visible: boolean): void;
}>();

// 提交状态
const loading = ref(false);
// 是否显示最大化切换按钮
const maxable = ref(true);
// 表格选中数据
const formRef = ref<FormInstance | null>(null);
const images = ref<ItemType[]>([]);
const durationDict = ref<DictData[]>([]);

// 用户信息
const form = reactive<ProjectRenew>({
  appRenewId: undefined,
  appId: undefined,
  appName: undefined,
  money: undefined,
  totalPrice: undefined,
  payPrice: undefined,
  reducePrice: undefined,
  duration: undefined,
  days: undefined,
  payType: 402,
  comments: undefined,
  startTime: undefined,
  endTime: undefined,
  soon: undefined,
  customerId: undefined,
  userId: undefined,
  images: undefined,
  nickname: undefined,
  tenantId: undefined,
  createTime: undefined,
  status: 0,
  fetching: false
});

/* 更新visible */
const updateVisible = (value: boolean) => {
  emit('update:visible', value);
};

// 表单验证规则
const rules = reactive({
  appId: [
    {
      required: true,
      type: 'number',
      message: '请选项项目',
      trigger: 'blur'
    }
  ],
  duration: [
    {
      required: true,
      type: 'number',
      message: '请选择续费时长',
      trigger: 'blur'
    }
  ],
  days: [
    {
      required: true,
      type: 'number',
      message: '请输入续费天数',
      trigger: 'blur'
    }
  ],
  payPrice: [
    {
      required: true,
      type: 'number',
      message: '请输入续费金额',
      trigger: 'blur'
    }
  ],
  payType: [
    {
      required: true,
      type: 'number',
      message: '请选择支付方式',
      trigger: 'blur'
    }
  ]
});

const onDone = (appId: number, item: Project) => {
  form.appId = appId;
  form.appName = item.appName;
  form.money = item.renewMoney;
  form.payPrice = item.renewMoney;
}

const chooseImage = (data: FileRecord) => {
  images.value.push({
    uid: data.id,
    url: data.path,
    status: 'done'
  });
  form.images = data.path;
};

const onDeleteItem = (index: number) => {
  images.value.splice(index, 1);
  form.images = '';
};

const handleDuration = () => {
  if(form.duration && form.money){
    form.totalPrice = Number(form.money) * Number(form.duration);
    form.payPrice = Number(form.money) * Number(form.duration);
  }
}

const handleDays = () => {
  // 计算每天的价格 form.money 价格
  const priceDay = Number(form.money) / 365;
  form.totalPrice = priceDay * Number(form.days);
  form.payPrice = priceDay * Number(form.days);
}

const {resetFields} = useForm(form, rules);

/* 保存编辑 */
const save = () => {
  if (!formRef.value) {
    return;
  }
  formRef.value
    .validate()
    .then(() => {
      loading.value = true;
      const formData = {
        ...form,
        images: JSON.stringify(images.value)
      };
      const saveOrUpdate = isUpdate.value ? updateProjectRenew : addProjectRenew;
      saveOrUpdate(formData)
        .then((msg) => {
          loading.value = false;
          message.success(msg);
          updateVisible(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          message.error(e.message);
        });
    })
    .catch(() => {
    });
};

let lastFetchId = 0;

const state = reactive<any>({
  data: [],
  value: undefined,
  fetching: false,
});

const fetchProject = debounce(value => {
  lastFetchId += 1;
  const fetchId = lastFetchId;
  state.data = [];
  state.fetching = true;
  pageProject({keywords: value})
    .then(body => {
      if (fetchId !== lastFetchId) {
        return;
      }
      state.data = body?.list.map(d => {
        d.label = d.appName;
        d.value = d.appId;
        return d
      }) || [];
      state.fetching = false;
    });
}, 300);

watch(state.value, () => {
  state.data = [];
  state.fetching = false;
});

listDictData({dictCode:'ProjectDuration'}).then(res => {
  durationDict.value = res.map(d => {
    d.label = d.dictDataName;
    d.value = Number(d.dictDataCode);
    return d;
  });
})

watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      fetchProject(undefined)
      images.value = [];
      if (props.data) {
        assignObject(form, props.data);
        isUpdate.value = true;
      } else {
        isUpdate.value = false;
      }
    } else {
      resetFields();
    }
  },
  {immediate: true}
);
</script>
