<template>
  <my-layout v-loading="loading" bg-fff>
    <layout-item>
      <div class="py-15px px-15px text-14px">
        <span class="cursor-pointer text-gray-500 hover:text-blue-500" @click="close()">返回</span>
        <el-divider direction="vertical" />
        <span class="text-15px">套餐管理</span>
        <el-icon class="transform translate-y-1px text-14px mx-3px">
          <ArrowRight />
        </el-icon>
        <span class="text-15px">{{data._id ?'编辑':'新增'}}套餐</span>
      </div>
    </layout-item>
    <Layout-main>
      <el-form class="px-15px pb-15px" :label-width="150" label-position="right" label-suffix="：">
        <div active-title-bar class="my-10px"><span class="text-16px font-semibold">基础信息</span></div>
        <el-form-item class="is-required" label="套餐名称">
          <el-input v-model="form.name" placeholder="请输入套餐名称" />
        </el-form-item>
        <el-form-item label="套餐描述">
          <el-input v-model="form.desc" :autosize="{ minRows: 5, maxRows: 8 }" resize="none" show-word-limit
            type="textarea" placeholder="请输入套餐描述" maxlength="500" />
        </el-form-item>
        <el-form-item label="是否有有效期">
          <div class="flex flex-grow flex-wrap">
            <el-checkbox v-model="form.hasValidDays" label="是" />
            <div v-if="form.hasValidDays" class="flex items-center flex-shrink-0 ml-10px">
              <span class="text-red-500">*</span>
              <span>请输入套餐有效期限：</span>
              <el-input v-model="form.validDays" placeholder="请输入天数" size="small" type="text" class="w-100px mx-5px"
                :formatter="formatInteger" />
              <span>天（付款成功之日起算）</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="折扣设置">
          <div class="flex flex-grow flex-wrap">
            <el-checkbox v-model="form.enableDiscount" label="支持折扣" />
            <div v-if="form.enableDiscount" class="flex items-center flex-shrink-0 ml-10px">
              <span>请输入最低折扣：</span>
              <el-input v-model="form.minDiscount" placeholder="请输入0-10的折扣" size="small" type="text"
                class="w-120px mx-5px" :formatter="formatNumber" />
              <span>折</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item class="is-required" label="所属分类">
          <el-cascader v-model="cateId" class="w-full" :show-all-levels="false" :options="cateTree"
            :props="{checkStrictly:true,value:'_id'}" clearable />
        </el-form-item>
        <div active-title-bar class="my-10px"><span class="text-16px font-semibold">套餐内容</span></div>
        <el-form-item class="is-required" label="套餐组合形式">
          <el-radio-group v-model="form.packageType">
            <el-radio v-for="item in ProjectPackageType" :key="item.value" :label="item.value" :value="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="form.packageType === 'fixed'">
          <el-form-item label="套餐项目">
            <div class="w-0 flex-grow pt-10px">
              <div class="text-14px mb-10px"><span class="cursor-pointer mr-5px text-blue-500"
                  @click="showProjectModal()">添加</span>
                <span class="text-gray-500"> 请添加项目，设置项目折扣价格计算套餐总价</span>
              </div>
              <el-table :data="tableProjects">
                <el-table-column prop="projectName" label="项目名称" :min-width="120" />
                <el-table-column prop="price" label="原单价" :min-width="100"></el-table-column>
                <el-table-column prop="number" label="数量" :min-width="120">
                  <template #default="{ row, $index }">
                    <el-input :model-value="row.number" placeholder="请输入数量" type="text" :formatter="formatInteger"
                      @update:model-value="changeProjectProp($event, 'number', $index)" />
                  </template>
                </el-table-column>
                <el-table-column prop="discount" label="折扣" :min-width="120">
                  <template #default="{ row, $index }">
                    <el-input :model-value="row.discount" placeholder="请输入折扣" type="text" :formatter="formatNumber"
                      @update:model-value="changeProjectProp($event, 'discount', $index)" />
                  </template>
                </el-table-column>
                <!-- <el-table-column prop="lowestDiscount" label="最低折扣" :min-width="120" /> -->
                <el-table-column prop="totalPrice" label="总价" :min-width="120" />
                <el-table-column prop="required" label="必选" width="80">
                  <template #default="{ row }">
                    <el-checkbox :model-value="true" />
                  </template>
                </el-table-column>
                <el-table-column fixed="right" align="center" class-name="el-table-fixed-column--shadow" label="操作"
                  width="100">
                  <template #default="{ row }">
                    <el-text type="danger" class="cursor-pointer mx-auto" @click="removeProject(row)">删除</el-text>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>
          <el-form-item label="套餐总价">
            <span class="text-red-500">￥{{allPrice}}</span>
          </el-form-item>
        </template>

        <template v-else-if="form.packageType === 'free'">
          <el-form-item class="is-required" label="套餐总价">
            <el-input class="w-200px mr-10px" v-model="form.packagePrice" placeholder="请输入套餐总价" type="text"
              :formatter="formatNumber">
              <template #suffix>元</template>
            </el-input>
            <span class="text-gray-500">自由组合形式，单项项目价格根据总价折扣平均计算</span>
          </el-form-item>
          <el-form-item class="is-required" label="套餐项目">
            <div class="w-0 flex-grow pt-10px">
              <div class="text-14px mb-10px"><span class="cursor-pointer mr-5px text-blue-500"
                  @click="showProjectModal()">添加</span>
                <span class="text-gray-500"> 请添加项目</span>
              </div>
              <el-table :data="tableProjects">
                <el-table-column prop="projectName" label="项目名称" :min-width="120" />
                <el-table-column prop="price" label="价格" :min-width="100"></el-table-column>
                <el-table-column prop="number" label="数量" :min-width="120">
                  <template #default="{ row, $index }">
                    <el-input :model-value="row.number" placeholder="请输入数量" type="text" :formatter="formatInteger"
                      @update:model-value="changeProjectProp($event, 'number', $index)" />
                  </template>
                </el-table-column>
                <el-table-column prop="totalPrice" label="总价" :min-width="120" />
                <el-table-column prop="required" label="必选" width="80">
                  <template #default="{ row, $index }">
                    <el-checkbox :model-value="row.required"
                      @update:model-value="changeProjectProp($event, 'required', $index)" />
                  </template>
                </el-table-column>
                <el-table-column fixed="right" align="center" class-name="el-table-fixed-column--shadow" label="操作"
                  width="100">
                  <template #default="{ row }">
                    <el-text type="danger" class="cursor-pointer mx-auto" @click="removeProject(row)">删除</el-text>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>
          <el-form-item class="is-required" label="项目可选项">
            <div class="flex-grow flex items-center">
              <el-input readonly class="w-100px"
                :model-value="form.projects && form.projects.length ? form.projects.length : 0 " />
              <span class="mx-10px">选</span>
              <el-input v-model="form.projectNumber" class="w-100px" :formatter="formatInteger"></el-input>
            </div>
          </el-form-item>
        </template>
      </el-form>
    </Layout-main>
    <Layout-item>
      <div class="text-center py-12px relative" common-shadow--r>
        <el-button plain class="w-100px" type="primary" @click="close()">取消</el-button>
        <el-button v-if="data._id" class="w-100px" type="danger" @click="remove()">删除</el-button>
        <el-button class="w-100px" :loading="loading" type="primary" @click="confirm()">确定</el-button>
      </div>
    </Layout-item>
  </my-layout>
  <project-picker selectWidthCate ref="projectPickerRef" :formatter="formatProjectPicker" :value="form.projects"
    :visible="projectModalVisible" :width="projectModalWidth" @close="closeProjectModal()" @change="changeProjects" />
</template>
<script setup>
import { computed, nextTick, onMounted, ref, watch } from "vue";
import { storeToRefs } from "pinia";
import { ElMessage, ElMessageBox } from "element-plus";
import BigNumber from "bignumber.js";
import { addProjectPackage, removeProjectPackage, updateProjectPackage, } from '@/api/member'
import { getProjectDiscount } from "@/api/project-manage";
import { ProjectPackageType } from "@/baseData";
import useModal from "@/hooks/useModal";
import { memberStore } from "@/store/member";

import projectPicker from "@/components/project-picker/project-picker.vue";
import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";

const emits = defineEmits(["close", 'change']);
const props = defineProps({
  data: { type: Object, default: () => ({}) },
  cateId: { type: String, default: '' },
  cateTree: { type: Array, default: () => [] }
})

const cateId = ref('');
const cateIdStr = computed(() => {
  if (typeof cateId.value === 'string') return cateId.value;
  return Array.isArray(cateId.value) ? cateId.value[cateId.value.length - 1] || '' : '';
})

const { memberInfo } = storeToRefs(memberStore());
const form = ref({})
const loading = ref(false)
const projectPickerRef = ref();
const { close: closeProjectModal, show: showProjectModal, visible: projectModalVisible, width: projectModalWidth } = useModal(800);
const tableProjects = computed(() => {
  const list = Array.isArray(form.value.projects) ? form.value.projects : [];
  return list.map(i => {
    const num = i.number > 0 ? Number(i.number) : 0;
    const price = i.price > 0 ? Number(i.price) : 0;
    const discount = form.value.packageType === 'free' ? 1 : (i.discount > 0 ? new BigNumber(i.discount).div(10).toNumber() : 0);
    return {
      ...i,
      totalPrice: (num > 0 && price > 0 && discount > 0) ? new BigNumber(num).times(price).times(discount).toNumber() : '',
    }
  })
})
const allPrice = computed(() => {
  const list = Array.isArray(tableProjects.value) ? tableProjects.value : [];
  const total = list.reduce((total, item) => {
    return total.plus(item.totalPrice > 0 ? Number(item.totalPrice) : 0)
  }, new BigNumber(0))
  return total.toNumber()
})

function changeProjectProp(val, prop, $index) {
  form.value.projects[$index][prop] = val
}

function changeProjects(data) {
  const projects = Array.isArray(form.value.projects) ? form.value.projects : [];
  const list = projects.filter(i => data.some(j => j._id === i._id)) // 已经存在的项目
  const ids = list.map(i => i._id)
  const newList = data.filter(i => !ids.some(j => j === i._id)).map(i => ({ ...i, number: 1, discount: 10 })) // 新增的项目
  form.value.projects = [...list, ...newList];
}

function close() {
  emits("close");
}

function confirm() {
  if (typeof form.value.name !== 'string' || form.value.name.trim() === '') {
    ElMessage.info('请输入套餐名称')
  } else if (form.value.hasValidDays === true && !form.value.validDays > 0) {
    ElMessage.info('请输入有效的套餐有效期限')
  } else if (form.value.enableDiscount === true && !(form.value.minDiscount > 0 && form.value.minDiscount <= 10)) {
    ElMessage.info('请输入有效的最低折扣')
  } else if (!cateIdStr.value) {
    ElMessage.info('请选择所属分类')
  } else if (!ProjectPackageType.some(i => i.value === form.value.packageType)) {
    ElMessage.info('套餐组合形式')
  } else if (form.value.packageType === 'free' && !(form.value.packagePrice) > 0) {
    ElMessage.info('请输入有效的套餐总价')
  } else if (!verifyProjects()) {

  } else if (form.value.packageType === 'free' && !(form.value.projectNumber > 0 && form.value.projectNumber <= form.value.projects.length)) {
    ElMessage.info('请输入有效的项目数目')
  } else {
    submit()
  }
}

async function remove() {
  await ElMessageBox.confirm('确定删除该套餐吗？', '提示', { type: 'warning' })
  const { success, message } = await removeProjectPackage({ corpId: memberInfo.value.corpId, id: form.value._id })
  if (success) {
    ElMessage.success(message)
    emits('change')
    close()
  } else {
    ElMessage.error(message)
  }
}
async function removeProject(project) {
  await ElMessageBox.confirm('确定删除该项目吗？', '提示', { type: 'warning' })
  form.value.projects = form.value.projects.filter((item) => item._id !== project._id);
}

async function submit() {
  const data = await getForm(form.value);
  const { success, message } = data._id ? await updateProjectPackage(data) : await addProjectPackage(data);
  if (success) {
    ElMessage.success(message)
    emits('change')
    close()
  } else {
    ElMessage.error(message)
  }
}


function formatInteger(val) {
  return formatNumber(val, true);
}

function formatProjectPicker(i) {
  return { _id: i._id, projectName: i.projectName, price: i.price, lowestDiscount: Number(i.lowestDiscount) > 0 ? Number(i.lowestDiscount) : 10, projectCateId: i.projectCateId };
}

function formatNumber(val, isInteger = false) {
  let str = String(val).replace(/[^\d.]/g, '');
  str = str.replace(/^\./, '');
  const formatted = str.replace(/^0+(?=\d|\.|$)/, '0');
  const [inter, decimal = ''] = formatted.split('.');
  let numStr = formatted.includes('.') ? `${inter}.${decimal}` : `${inter}`;
  if (isInteger) {
    return numStr.split('.')[0];
  } else {
    let parts = numStr.split('.');
    if (parts.length > 1) {
      parts[1] = parts[1].slice(0, 2);
      numStr = parts.join('.');
    }
    return numStr;
  }
}

function verifyProjects() {
  if (!Array.isArray(form.value.projects) || form.value.projects.length === 0) {
    ElMessage.info('请添加项目');
    return false;
  }
  for (let project of form.value.projects) {
    if (!(project.number > 0)) {
      ElMessage.info(`${project.projectName}：请输入有效的数量`);
      return false;
    }
    const discount = project.discount > 0 ? Number(project.discount) : 0;
    if (form.value.packageType === 'fixed' && !(discount <= 10 && discount > 0)) {
      ElMessage.info(`${project.projectName}：请输入有效的折扣`);
      return false
    }
    if (form.value.packageType === 'fixed' && !(discount >= project.lowestDiscount)) {
      ElMessage.info(`${project.projectName}的最低折扣为${project.lowestDiscount}折`);
      return false
    }
  }
  return true
}

async function getForm(params, init = false) {
  const data = {
    corpId: memberInfo.value.corpId,
    cateId: cateIdStr.value,
    name: typeof params.name === 'string' ? params.name.trim() : '',
    desc: typeof params.desc === 'string' ? params.desc.trim() : '',
    hasValidDays: typeof params.hasValidDays === 'boolean' ? params.hasValidDays : false,
    validDays: params.validDays > 0 ? Number(params.validDays) : '',
    enableDiscount: typeof params.enableDiscount === 'boolean' ? params.enableDiscount : false,
    minDiscount: params.minDiscount > 0 ? Number(params.minDiscount) : '',
    packageType: ProjectPackageType.some(i => i.value === params.packageType) ? params.packageType : '',
    packagePrice: params.packagePrice > 0 ? Number(params.packagePrice) : '',
    projects: Array.isArray(params.projects) ? params.projects.map(i => ({
      _id: i._id,
      projectCateId: i.projectCateId,
      projectName: typeof i.projectName === 'string' ? i.projectName.trim() : '',
      price: Number(i.price) > 0 ? Number(i.price) : '',
      number: Number(i.number) > 0 ? Number(i.number) : '',
      discount: Number(i.discount) > 0 ? Number(i.discount) : '',
      totalPrice: Number(i.totalPrice) > 0 ? Number(i.totalPrice) : '',
      lowestDiscount: Number(i.lowestDiscount) > 0 ? Number(i.lowestDiscount) : 10,
      required: params.packageType === 'fixed' ? true : (typeof i.required === 'boolean' ? i.required : false)
    })) : [],
    projectNumber: params.projectNumber > 0 ? Number(params.projectNumber) : '',
  }
  if (params.packageType === 'fixed') {
    data.packagePrice = allPrice.value
    data.projectNumber = data.projects.length
  };

  if (params._id) {
    data._id = params._id;
  };
  if (init) {
    loading.value = true;
    const projectIds = data.projects.map(i => i._id);
    const { data: res } = projectIds.length ? (await getProjectDiscount({ corpId: memberInfo.value.corpId, projectIds })) : {};
    const discountSet = res && Array.isArray(res.data) ? res.data.reduce((m, i) => {
      if (i._id) {
        m.set(i._id, Number(i.lowestDiscount) > 0 ? Number(i.lowestDiscount) : 10)
      }
      return m
    }, new Map()) : new Map();
    data.projects.forEach(i => (i.lowestDiscount = discountSet.get(i._id) || 10))
    loading.value = false;
  }
  return data
}

onMounted(async () => {
  cateId.value = props.cateId;
  form.value = await getForm(props.data, true);
  await nextTick()
})

</script>
<style lang="scss" scoped>
.el-input-border {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}
</style>
