<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <!--店铺名称、负责人、联系人、推广人、店铺类型、地址、签约状态 -->
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="名称:" prop="storeName" label-width="100px">
              <el-input v-model="queryParams.templateName" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="类型:" prop="isActive" label-width="100px">
              <el-select v-model="queryParams.isActive" placeholder="请选择类型" clearable>
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['tenant:divide:add']">新增</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="tenantList">
        <el-table-column v-if="false" label="id" align="center" prop="id" />
        <el-table-column label="名称" align="center" prop="templateName" />
        <el-table-column label="类型" align="center" prop="templateType">
          <template #default="scope">
            {{ scope.row.templateType == 1 ? '商品' : '成交额' }}
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center" prop="description" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="更新时间" align="center" prop="updateTime" />

        <el-table-column width="180" label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="增加规则" placement="top" v-hasPermi="['tenant:divide:add']">
              <el-button link type="primary" @click="funseach(scope.row)">
                <el-icon><Plus /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top" v-hasPermi="['tenant:divide:update']">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" v-hasPermi="['tenant:divide:delete']">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:current="queryParams.current" v-model:size="queryParams.size" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加/修改模板 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" append-to-body>
      <el-form ref="tenantFormRef" :model="form" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="名称" prop="templateName">
              <el-input v-model="form.templateName" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="templateType">
              <el-select v-model="form.templateType" placeholder="请选择类型">
                <el-option label="商品" value="1" />
                <el-option label="成交额" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="描述" prop="description">
              <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入描述" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看模板 -->
    <el-dialog v-model="sexDialog.visible" :title="sexDialog.title" width="800px" append-to-body>
      <el-form ref="secformRef" :model="secform" v-if="mul == '1'">
        <el-button type="primary" plain icon="Plus" @click="addform" style="margin-bottom: 10px">新增</el-button>
        <el-row :gutter="20" v-for="(item, index) in templateDetailList" :key="index">
          <el-col :span="12">
            <el-form-item label="种类:" :prop="'templateDetailList[' + index + '].rateName'">
              <el-select v-model="item.rateName" placeholder="请选择" clearable>
                <el-option v-for="item in enterpriseList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="比例:" :prop="'templateDetailList[' + index + '].rate'">
              <el-input v-model="item.rate" type="text" placeholder="请输入0.00" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="" prop="templateType">
              <el-button link type="primary" icon="Delete" @click="deleteList(index, item.id)"></el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- //区间 -->
      <el-form ref="constdfromRef" :model="secform" :rules="constfrules" v-else>
        <el-button type="primary" plain icon="Plus" @click="conadd" style="margin-bottom: 10px">新增</el-button>
        <el-row :gutter="20" v-for="(item, index) in constdfrom" :key="index">
          <el-col :span="7">
            <el-form-item label="小于:" :prop="'constdfrom[' + index + '].minAmount'">
              <el-input v-model="item.minAmount" type="text" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="大于:" :prop="'constdfrom[' + index + '].maxAmount'">
              <el-input v-model="item.maxAmount" type="text" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="比例:" :prop="'constdfrom[' + index + '].rate'">
              <el-input v-model="item.rate" type="text" placeholder="请输入0.00" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-form-item label="" prop="templateType">
              <el-button link type="primary" icon="Delete" @click="condele(index, item.id)"></el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="addsectionasync">确 定</el-button>
          <el-button @click="clearfun">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tenant" lang="ts">
import { listDivide, addTenant, addsection, getsections, putsections, deletesection, delTenant, updateTenant } from '@/api/system/divide';
import { TenantForm, TenantQuery, TenantVO } from '@/api/system/types';
import { getDictionaryByKey } from '@/utils/dict';
import { selectTenantPackage } from '@/api/system/tenantPackage';
import { useUserStore } from '@/store/modules/user';
// import { TenantForm, TenantQuery, TenantVO, TenantModal, enterpriseType } from '@/api/system/tenant/types';
import { TenantPkgVO } from '@/api/system/tenantPackage/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const userStore = useUserStore();

const tenantList = ref<TenantVO[]>([]);
const packageList = ref<TenantPkgVO[]>([]);

const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const tenantFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const sexDialog = ref<DialogOption>({
  visible: false,
  title: ''
});
//商品
const templateDetailList = ref([]);

const secform = ref({
  templateId: '',
  templateList: ''
});
const addform = () => {
  templateDetailList.value.push({
    rateName: '',
    rate: ''
  });
};
const deleteList = (index: any, id: any) => {
  templateDetailList.value.splice(index, 1);
  if (id) {
    deletesection(id);
  }
};
//成交额
const constdfrom = ref([]);
const conadd = () => {
  constdfrom.value.push({
    minAmount: '',
    maxAmount: '',
    rate: ''
  });
};
const condele = (index: any, id: any) => {
  constdfrom.value.splice(index, 1);
  if (id) {
    deletesection(id);
  }
};
const constfrules = ref({
  minAmount: [
    { required: true, message: '请输入最小金额', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,4})?$/, message: '金额格式应为数字，最多保留四位小数', trigger: 'blur' }
  ],
  maxAmount: [
    { required: true, message: '请输入最大金额', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,4})?$/, message: '金额格式应为数字，最多保留四位小数', trigger: 'blur' }
  ],
  rate: [
    { required: true, message: '请输入比例', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,4})?$/, message: '比例格式应为数字，最多保留四位小数', trigger: 'blur' }
  ]
});
const mul = ref<string>('');
const isFuttl = ref<boolean>(false);
//详情数据
const funseach = (data: any) => {
  // getTenantPackage();
  templateDetailList.value = [];
  constdfrom.value = [];
  sexDialog.value.visible = true;
  secform.value.templateId = data.id;
  mul.value = data.templateType;
  sexDialog.value.title = '模板详情';
  getsections({ 'templateId': data.id }).then((res: any) => {
    if (res.code == 200) {
      if (data.templateType == '1') {
        // isFuttl.value = true;

        res.data.forEach((item: any) => {
          templateDetailList.value.push({
            rateName: item.rateName,
            rate: item.rate,
            id: item.id
          });
        });
      } else {
        res.data.forEach((item: any) => {
          constdfrom.value.push({
            minAmount: item.minAmount,
            maxAmount: item.maxAmount,
            rate: item.rate,
            id: item.id
          });
        });
      }
    }
  });
};
const secformRef = ref<ElFormInstance>();
const constdfromRef = ref<ElFormInstance>();
//模板比例添加
const addsectionasync = async () => {
  addsecfun();
};
const addsecfun = () => {
  if (mul.value == '1') {
    secformRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        secform.value.templateList = JSON.stringify(templateDetailList.value);
        const res = await addsection(secform.value);
        if (res.code == 200) {
          ElMessage.success('新增成功');
          sexDialog.value.visible = false;
          getList();
          secform.value = {
            templateId: '',
            templateList: ''
          };
          templateDetailList.value = [];
        }
      }
    });
  } else {
    constdfromRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        secform.value.templateList = JSON.stringify(constdfrom.value);
        const res = await addsection(secform.value);
        if (res.code == 200) {
          ElMessage.success('新增成功');
          sexDialog.value.visible = false;
          getList();
          secform.value = {
            templateId: '',
            templateList: ''
          };
          constdfrom.value = [];
        }
      }
    });
  }
};
const clearfun = () => {
  sexDialog.value.visible = false;
  secform.value.templateId = '';
  secform.value = {
    templateId: '',
    templateList: ''
  };
};
const enterpriseList = ref([]); // 种类
const getByKey = async () => {
  const value1 = await getDictionaryByKey('rate_name');
  enterpriseList.value = value1;
};
const initFormData: TenantForm = {
  id: null,
  templateName: '',
  templateType: '',
  description: ''
};

const data = reactive<PageData<TenantForm, TenantQuery>>({
  form: { ...initFormData },
  queryParams: {
    current: 1,
    size: 10,
    templateName: '',
    isActive: ''
  },
  rules: {
    id: [{ required: true, message: 'id不能为空', trigger: 'blur' }],
    templateName: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
    templateType: [{ required: true, message: '模板类型不能为空', trigger: 'blur' }],
    description: [{ required: true, message: '模板描述不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询所有租户套餐 */
const getTenantPackage = async () => {
  const res = await selectTenantPackage();
  packageList.value = res.data;
};

/** 查询租户列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDivide(queryParams.value);
  tenantList.value = res.data.records;
  total.value = res.data.total;
  loading.value = false;
};

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
};

// 表单重置
const reset = () => {
  form.value = { ...initFormData };
  tenantFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.current = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

// // 多选框选中数据
// const handleSelectionChange = (selection: TenantVO[]) => {
//   ids.value = selection.map((item) => item.id);
//   single.value = selection.length != 1;
//   multiple.value = !selection.length;
// };

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  // getTenantPackage();
  dialog.visible = true;
  dialog.title = '新增模板';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TenantVO) => {
  reset();
  // await getTenantPackage();
  const _id = row?.id;
  // const res = await getTenant(_id);
  Object.assign(form.value, row);
  dialog.visible = true;
  dialog.title = '修改模板';
};

/** 提交按钮 */
const submitForm = () => {
  tenantFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateTenant(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTenant(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TenantVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除租户编号为"' + _ids + '"的数据项？');
  loading.value = true;
  await delTenant(_ids).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

onMounted(() => {
  getByKey();
  getList();
});
</script>
<style scoped lang="scss"></style>
