<template>
  <div class="max-h-[calc(100vh-250px)] overflow-auto">
    <h6 class="title">城市人口及年龄参数</h6>
    <el-table class="c-table"
              :data="form.ageAduRatioList"
              :span-method="ageSpan"
              border>
      <el-table-column prop="productName"
                       label="城市总人口 (人)"
                       align="center">
        <template #default="{ row }">
          <el-input v-model.number="row.totalPopulation"
                    placeholder="请输入"
                    type="number"
                    min="0"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="ageStage"
                       label="年龄 (岁)"
                       align="center"></el-table-column>
      <el-table-column prop="ageRatio"
                       label="年龄占比 (%)"
                       align="center">
        <template #default="{ row }">
          <el-input v-model="row.ageRatio"
                    placeholder="请输入"></el-input>
        </template>
      </el-table-column>
    </el-table>

    <h6 class="title mt-7">学历参数</h6>
    <el-table class="c-table"
              :data="edus"
              :span-method="eduSpan"
              border>
      <el-table-column prop="ageStage"
                       label="年龄 (岁)"
                       align="center"> </el-table-column>
      <el-table-column prop="education"
                       label="学历"
                       align="center"></el-table-column>
      <el-table-column prop="parentIds"
                       label="学历占比 (%)"
                       align="center">
        <template #default="{ row }">
          <el-input v-model="row.eduRatio"
                    placeholder="请输入"></el-input>
        </template>
      </el-table-column>
    </el-table>

    <h6 class="title mt-7">企业数量配置</h6>
    <el-table class="c-table"
              :data="form.enterpriseNumList"
              border>
      <el-table-column prop="productName"
                       label="企业类型"
                       align="center">
        <template #default="{ row }">
          {{ row.enterpriseType == 1 ? '小微企业' : '创业企业' }}
        </template>
      </el-table-column>
      <el-table-column prop="parentIds"
                       label="企业数量（家）"
                       align="center">
        <template #default="{ row }">
          <el-input v-model.number="row.number"
                    placeholder="请输入"
                    maxlength="3"
                    type="number"
                    min="0"></el-input>
        </template>
      </el-table-column>
    </el-table>

    <h6 class="title mt-7">单个商品每日需求量</h6>
    <el-table class="c-table"
              :data="form.commodityDemandList"
              border>
      <el-table-column prop="typeName"
                       label="买家类型"
                       min-width="100"
                       align="center"> </el-table-column>
      <el-table-column prop="parentIds"
                       label="买家总占比 (%)"
                       min-width="100"
                       align="center">
        <template #default="{ row }">
          <el-input v-model="row.buyerRatio"
                    placeholder="请输入"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="parentIds"
                       label="每次需求人数占比 (%)"
                       min-width="130"
                       align="center">
        <template #default="{ row }">
          <el-input v-model="row.peopleNumRatio"
                    placeholder="请输入"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="parentIds"
                       label="单个买家单次需求"
                       min-width="200"
                       align="center">
        <template #default="{ row }">
          <div class="flex items-center">
            <template v-if="row.typeId == 7 || row.typeId == 8">
              <span class="mr-2 whitespace-nowrap">一个保险产品一次最多购买</span>
              <el-input v-model="row.buyerSingleDemand"
                        placeholder="请输入"></el-input>
              <span class="ml-2">份</span>
            </template>
            <template v-else>
              <span class="mr-2 whitespace-nowrap">{{ row.typeId == 9 ? '投入' : '贷款' }}</span>
              <el-input v-model="row.buyerSingleDemandMin"
                        placeholder="请输入"></el-input>
              <span class="mx-2">~</span>
              <el-input v-model="row.buyerSingleDemandMax"
                        placeholder="请输入"></el-input>
              <span class="ml-2 whitespace-nowrap">万元</span>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <h6 class="title mt-7">系统账户起始金额</h6>
    <el-form v-if="form.moneyAllocationList.length"
             class="w-[300px]"
             label-width="120px"
             label-suffix="：">
      <el-form-item label="银行账户">
        <el-input v-model="form.moneyAllocationList[0].startingAmount">
          <template #suffix> 万元 </template>
        </el-input>
      </el-form-item>
      <el-form-item label="保险账户">
        <el-input v-model="form.moneyAllocationList[1].startingAmount">
          <template #suffix> 万元 </template>
        </el-input>
      </el-form-item>
      <el-form-item label="基金账户">
        <el-input v-model="form.moneyAllocationList[2].startingAmount">
          <template #suffix> 万元 </template>
        </el-input>
      </el-form-item>
    </el-form>
  </div>

  <div class="flex justify-end">
    <div class="submit"
         @click="submit">保存修改</div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import type { TableColumnCtx } from 'element-plus';
import { isIllegalNum } from '@/utils/common';
import { saveOrUpdate, systemBuyerFind, ages, edu, accountType, buyerType } from '@/api/config';
import _ from 'lodash';

const added = ref<number>(0);
const edus = ref<Record<string, any>[]>([]);
const form = ref<Record<string, any>>({
  ageAduRatioList: [],
  commodityDemandList: [],
  enterpriseNumList: [
    {
      enterpriseType: 1,
      number: '',
    },
    {
      enterpriseType: 2,
      number: '',
    },
  ],
  moneyAllocationList: [],
});

// 配置项
const getInfo = async () => {
  edus.value = [];
  const res = await edu();

  const { list } = await ages();
  list.map((e) => {
    res.list.map((n) => {
      edus.value.push({
        eduRatio: '',
        ...n,
        ...e,
      });
    });

    e.ageRatio = '';
    e.totalPopulation = '';
  });
  form.value.ageAduRatioList = list;

  const { data } = await buyerType();
  data.map((e) => {
    e.buyerRatio = '';
    e.buyerSingleDemand = '';
    e.buyerSingleDemandMin = '';
    e.buyerSingleDemandMax = '';
    e.peopleNumRatio = '';
  });
  form.value.commodityDemandList = data;

  const res1 = await accountType();
  res1.list.map((e) => {
    e.startingAmount = '';
  });
  form.value.moneyAllocationList = res1.list;

  // 以上的是每个模块的每行名称，下面的是整块的详情
  const { systemBuyerDTO } = await systemBuyerFind();
  if (systemBuyerDTO.ageAduRatioList.length) {
    edus.value = _.merge(edus.value, systemBuyerDTO.ageAduRatioList.splice(6));
    added.value = 1;
  }
  systemBuyerDTO.commodityDemandList.map((e) => {
    if (e.typeId != 7 && e.typeId != 8 && e.buyerSingleDemand.includes('-')) {
      const val = e.buyerSingleDemand.split('-');
      e.buyerSingleDemandMin = val[0];
      e.buyerSingleDemandMax = val[1];
    }
  });
  _.merge(form.value, systemBuyerDTO);
  console.log('🚀 ~ file: Buyer.vue:236 ~ getInfo ~ form.value:', form.value);
};

const submit = async () => {
  const param = JSON.parse(JSON.stringify(form.value));
  let invalid = 0;

  // 年龄
  if (isIllegalNum(param.ageAduRatioList[0].totalPopulation)) return ElMessage.error('请输入合理的城市总人口');
  param.ageAduRatioList.some((e) => {
    if (isIllegalNum(e.ageRatio)) {
      ElMessage.error('请输入合理的年龄占比');
      invalid = 1;
      return true;
    }
  });
  if (invalid) return false;
  if (_.sum(param.ageAduRatioList.map((e) => +e.ageRatio)) > 100) return ElMessage.error('占比总和不得超过100%');

  // 学历
  edus.value.some((e) => {
    if (isIllegalNum(e.eduRatio)) {
      ElMessage.error('请输入合理的学历占比');
      invalid = 1;
      return true;
    }
  });
  if (invalid) return false;

  // 企业数量配置
  param.enterpriseNumList.some((e) => {
    if (isIllegalNum(e.number)) {
      ElMessage.error('请输入合理的企业数量');
      invalid = 1;
      return true;
    }
  });
  if (invalid) return false;

  // 单个商品每日需求量
  param.commodityDemandList.some((e) => {
    if (isIllegalNum(e.buyerRatio) || e.buyerRatio > 100) {
      ElMessage.error('请输入合理的买家总占比');
      invalid = 1;
      return true;
    }
    if (isIllegalNum(e.peopleNumRatio) || e.peopleNumRatio > 100) {
      ElMessage.error('请输入合理的每次需求人数占比');
      invalid = 1;
      return true;
    }

    if (e.typeId != 7 && e.typeId != 8 && (isIllegalNum(e.buyerSingleDemandMin) || isIllegalNum(e.buyerSingleDemandMax))) {
      ElMessage.error('请输入合理的单个买家单次需求');
      invalid = 1;
      return true;
    }

    if ((e.typeId == 7 || e.typeId == 8) && isIllegalNum(e.buyerSingleDemand)) {
      ElMessage.error('请输入合理的单个买家单次需求');
      invalid = 1;
      return true;
    }
  });
  if (invalid) return false;

  // 系统账户起始金额
  if (param.moneyAllocationList[0].startingAmount === '' || isNaN(param.moneyAllocationList[0].startingAmount)) return ElMessage.error('请输入合理的银行账户');
  if (param.moneyAllocationList[1].startingAmount === '' || isNaN(param.moneyAllocationList[1].startingAmount)) return ElMessage.error('请输入合理的保险账户');
  if (param.moneyAllocationList[2].startingAmount === '' || isNaN(param.moneyAllocationList[2].startingAmount)) return ElMessage.error('请输入合理的基金账户');

  param.ageAduRatioList.push(...edus.value);
  param.commodityDemandList.map((e) => {
    if (e.buyerSingleDemandMin && e.buyerSingleDemandMax) e.buyerSingleDemand = `${e.buyerSingleDemandMin}-${e.buyerSingleDemandMax}`;
  });
  await saveOrUpdate(param);
  ElMessage.success('保存成功！');
  getInfo();
};

interface SpanMethodProps {
  row: Record<string, any>;
  column: TableColumnCtx<Record<string, any>>;
  rowIndex: number;
  columnIndex: number;
}
// 人口及年龄表格合并
const ageSpan = ({ row, column, rowIndex, columnIndex }: SpanMethodProps) => {
  if (columnIndex === 0) {
    if (rowIndex === 0) {
      return {
        rowspan: 6,
        colspan: 1,
      };
    }
    return {
      rowspan: 0,
      colspan: 0,
    };
  }
};
// 学历表格合并
const eduSpan = ({ row, column, rowIndex, columnIndex }: SpanMethodProps) => {
  if (columnIndex === 0) {
    if (rowIndex % 4 === 0) {
      return {
        rowspan: 4,
        colspan: 1,
      };
    }
    return {
      rowspan: 0,
      colspan: 0,
    };
  }
};

onMounted(() => {
  getInfo();
});
</script>

<style lang="scss" scoped>
@import url(../../../styles/form.scss);
.title {
  @apply flex items-center mb-5 text-base text-[#222D42] font-semibold;
  &:before {
    content: '';
    @apply w-1 h-4 mr-2 bg-[#006BFF] rounded-sm;
  }
}
</style>
