<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @drag-sort="sortTable"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <!-- <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增商铺及商铺管理员</el-button> -->
        <el-button type="primary" :icon="CirclePlus" @click="handleToDetail('add', '')"> 新增 </el-button>
        <el-button type="primary" :icon="Download" @click="exportInfoExcel()"> 导出 </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" v-if="scope.row.storeApplicationStatus == 0" link :icon="Check" @click="approve(1, scope.row)">
          通过
        </el-button>
        <!-- <el-button type="primary" v-if="scope.row.storeApplicationStatus == 0" link :icon="Close"
          @click="approve(2, scope.row)">拒绝</el-button> -->

        <el-button type="primary" v-if="scope.row.storeApplicationStatus == 0" link :icon="Close" @click="jj(scope.row)">
          拒绝
        </el-button>

        <el-button type="primary" link :icon="Search" @click="handleToDetail('show', scope.row.id)"> 查看详情 </el-button>
        <el-button
          v-if="scope.row.storeStatus != 2"
          type="primary"
          link
          :icon="EditPen"
          @click="handleToDetail('edit', scope.row.id)"
        >
          编辑
        </el-button>
        <el-button
          v-if="scope.row.storeApplicationStatus != 0"
          type="primary"
          link
          :icon="Delete"
          @click="deleteAccount(scope.row)"
        >
          删除
        </el-button>
        <el-button type="primary" link :icon="PieChart" @click="handleCC(scope.row)" v-if="scope.row.storeStatus !== 2">
          设置抽成比例
        </el-button>
      </template>
    </ProTable>
    <StoreUserDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
    <!--  设置抽成百分比弹出框-->
    <el-drawer v-model="drawer" :direction="direction" size="89%">
      <template #header>
        <h4>商家管理/店铺管理</h4>
      </template>
      <template #default>
        <div class="topTitle">当前店铺订单抽成比例：{{ ccValuefix || 0 }}%</div>
        <div class="inputcc">
          <span>设置抽成比例</span>
          <div>
            <el-input
              style="width: 100%"
              placeholder="请输入0~100的抽成比例"
              type="number"
              size="large"
              v-model="ccValue"
              :min="0"
              :max="100"
              @change="changeCCValue"
            >
              <template #append>
                <span>% / 每单</span>
              </template>
            </el-input>
          </div>
        </div>
        <div class="topTitle zysx">
          <span>计算说明</span>
          <div>
            <span>订单金额x抽成比例=平台抽成金额</span>
            <br />
            <span>例如：订单金额100元，抽成比例3%，则平台抽成为3元</span>
          </div>
        </div>
        <div class="topTitle zysx zysx2">
          <span>注意</span>
          <div>
            <span>1.修改抽成比例将影响所有新生产的订单</span>
            <br />
            <span>2.已完成订单的抽成比例不受影响</span>
            <br />
            <span>3.建议根据市场情况合理设置抽成比例</span>
          </div>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick"> 取消 </el-button>
          <el-button type="primary" @click="confirmClick"> 确定 </el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 拒接弹窗 -->
    <el-dialog v-model="dialogFormVisible" title="温馨提示" width="500">
      <div style="padding-bottom: 2vh; font-size: 15px; font-weight: 700">是否拒绝【{{ jjValue?.storeName }}】商铺申请?</div>
      <el-form :model="form">
        <el-form-item label="拒绝原因：" :label-width="formLabelWidth">
          <el-input v-model="form.reason" autocomplete="off" :rows="2" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false"> 取消 </el-button>
          <el-button type="primary" @click="jjQd"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { useRouter, useRoute } from "vue-router";
import { ref, reactive, computed, onMounted, watch, onUnmounted, onActivated } from "vue";
import { StoreUser } from "@/api/interface";
import { ElMessage } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import StoreUserDrawer from "@/views/proTable/components/StoreUserDrawer.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Download, Upload, Refresh, Check, Close, Search, PieChart } from "@element-plus/icons-vue";
import {
  getStoreUserList,
  addStoreUser,
  editStoreUser,
  deleteStoreUser,
  resetStoreUserPassWord,
  getStoreInfoList,
  getBusinessSection,
  deleteStoreInfo,
  approveStoreInfo,
  exportExcel,
  updateStoreCommissionRate
} from "@/api/modules/storeUser";
import { useHandleData } from "@/hooks/useHandleData";
import { number } from "echarts";
import type { DrawerProps } from "element-plus";
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const form = reactive({
  reason: ""
});
const router = useRouter();
const route = useRoute();
watch(
  () => route.fullPath,
  (newVal, oldVal) => {
    if (newVal.startsWith("/store/storeUser") && newVal !== oldVal) {
      proTable.value?.getTableList();
    }
  },
  { immediate: true }
);

//导出信息
const exportInfoExcel = async () => {
  const params = (proTable.value?.searchParam as Record<string, any>) ?? {};
  let res = await exportExcel(params);
  console.log("导出res", res);
  // link.href = "https://file.ailien.shop/excel/generate/storeCashOutRecord4.xlsx";
  if (res.code == "200") {
    if (!res.data) {
      ElMessage.error("暂无可下载数据");
      return;
    }
    const exportFile = document.createElement("a");
    exportFile.style.display = "none";
    exportFile.download = `商铺信息.xlsx`;
    // return;
    exportFile.href = `${res.data}?timestamp=${new Date().getTime()}`; // 添加时间戳防止缓存
    // exportFile.href = ` https://file.ailien.shop/excel/generate/storeCashOutRecord4.xlsx?timestamp=${new Date().getTime()}`; // 添加时间戳防止缓存
    https: document.body.appendChild(exportFile);
    exportFile.click();
    // 去除下载对 url 的影响
    document.body.removeChild(exportFile);
    ElMessage.success("下载成功");
  }
};

//审批状态
const approve = async (approvalStatus: number, row: StoreUser.ResStoreUserList) => {
  if (!row.expirationTime) {
    ElMessage.error("请先选择商铺的到期时间");
    return;
  }
  let approvalStatusStr = approvalStatus == 1 ? "通过" : "拒绝";
  approvalStatusStr += "【" + row.storeName + "】商铺申请?";
  await useHandleData(approveStoreInfo, { id: row.id, approvalStatus: approvalStatus }, approvalStatusStr);
  proTable.value?.getTableList();
};

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success("修改列表排序成功");
};

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.records,
    total: data.total
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  // newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  // newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  // delete newParams.createTime;
  return getStoreInfoList(newParams);
};

// 门店审核状态列表
const storeApplicationStatus = ref<any[]>([
  { value: 0, label: "待审核" },
  { value: 1, label: "审核通过" },
  { value: 2, label: "审核拒绝" }
]);

// 门店状态列表
const storeStatuss = ref<any[]>([
  { value: 1, label: "正常" },
  { value: 0, label: "禁用" },
  { value: 2, label: "已注销" }
]);

//获取审批状态列表
const getAuditStatus = computed((params: any) => {
  const list: any = [];
  list.push({ auditLabel: "待审核", auditValue: "0" });
  list.push({ auditLabel: "审核通过", auditValue: "1" });
  list.push({ auditLabel: "审核拒绝", auditValue: "2" });
  return list;
});

// 经营板块列表
const businessSectionList = ref<any[]>([]);

const getBusinessSectionList = async () => {
  const res = await getBusinessSection();
  const addData: any[] = [];
  const data = (res as any)?.data ?? [];
  data.forEach((element: any) => {
    addData.push({
      value: Number(element.dictId),
      label: element.dictDetail,
      parentId: element.parentId
    });
  });
  businessSectionList.value = addData;
};

// 表格配置项
const columns = reactive<ColumnProps<StoreUser.ResStoreUserList>[]>([
  { type: "selection", fixed: "left" },
  { prop: "id", label: "商铺ID", search: { el: "input", tooltip: "请输入商铺id" } },
  { prop: "storeContact", label: "联系人" },
  { prop: "storePhone", label: "联系电话", search: { el: "input", tooltip: "请输入联系人电话" } },
  { prop: "storeName", label: "店铺名称" },
  {
    prop: "businessSection",
    label: "经营板块",
    enum: businessSectionList,
    search: { el: "select" },
    fieldNames: { label: "label", value: "value" }
  },
  {
    prop: "createdTime",
    label: "创建时间",
    width: 180,
    search: {
      span: 2,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" },
      defaultValue: ["2022-11-12 11:35:00", "2022-12-12 11:35:00"]
    }
  },
  {
    prop: "storeApplicationStatus",
    label: "审核状态 ",
    search: { el: "select" },
    enum: storeApplicationStatus,
    fieldNames: { label: "label", value: "value" }
  },
  {
    prop: "storeStatus",
    label: "状态 ",
    enum: storeStatuss,
    fieldNames: { label: "label", value: "value" }
  },

  // { prop: "storeTypeStr", label: "经营类型" },
  // { prop: "businessStatusStr", label: "状态" },
  { prop: "operation", label: "操作", fixed: "right", width: 330 }
]);

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof StoreUserDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<StoreUser.ResStoreUserList> = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    api: title === "新增" ? addStoreUser : title === "编辑" ? editStoreUser : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};

// 删除商户信息
const deleteAccount = async (params: StoreUser.ResStoreUserList) => {
  await useHandleData(deleteStoreInfo, { id: params.id }, `删除【${params.storeName}】商铺与管理账户`);
  proTable.value?.getTableList();
};

// 重置用户密码
const resetPass = async (params: StoreUser.ResStoreUserList) => {
  await useHandleData(resetStoreUserPassWord, { id: params.id }, `重置【${params.storeName}】】商铺与管理账户密码`);
  proTable.value?.getTableList();
};

//跳转至新增页面
const handleToDetail = (type: string, id?: string) => {
  router.push({
    path: `/store/storeInfo/storeInfoDetail`,
    query: {
      id: id,
      type: type
    }
  });
  // router.push(`/store/storeInfo/storeInfoDetail`);
};

onMounted(async () => {
  //获取商铺经营板块
  await getBusinessSectionList();
  await getTableList({});
});

onActivated(() => {
  proTable.value?.getTableList();
});
//抽成比例部分
const ccValue = ref(30);
const ccValuefix = ref(30);
const drawer = ref(false);
const direction = ref<DrawerProps["direction"]>("rtl");
function cancelClick() {
  drawer.value = false;
}
const storeId = ref("");
const confirmClick = async () => {
  let params = {
    id: storeId.value,
    commissionRate: ccValue.value
  };
  let res = await updateStoreCommissionRate(params);
  if (res.code == "200") {
    ElMessage.success("设置抽成比例成功！");
    ccValuefix.value = ccValue.value;
    drawer.value = false;
    proTable.value?.getTableList();
  } else {
    ElMessage.error("设置抽成比例失败！");
  }
};
//这个是为了不让输入框输入超过100%
function changeCCValue() {
  if (ccValue.value < 0) {
    ccValue.value = 0;
  } else if (ccValue.value > 100) {
    ccValue.value = 100;
  }
}
//点击抽成百分比
const handleCC = (item: any) => {
  console.log(item, "点击抽成百分比");
  storeId.value = item.id;
  ccValue.value = item.commissionRate;
  ccValuefix.value = item.commissionRate;
  drawer.value = true;
};
const jjValue = ref<any>({});
// 点击拒接
const jj = (item: any) => {
  dialogFormVisible.value = true;
  form.reason = "";
  jjValue.value = item;
};
// 点击拒绝确定
const jjQd = async () => {
  let res = await approveStoreInfo({
    id: jjValue.value.id,
    approvalStatus: 2,
    reason: form.reason
  });
  if (res.code == "200") {
    dialogFormVisible.value = false;
    proTable.value?.getTableList();
    ElMessage.success("审核拒绝成功！");
  } else {
    ElMessage.error("审核拒绝失败！");
  }
};
</script>

<style scoped lang="scss">
.topTitle {
  width: 100%;
  padding: 14px;
  margin-bottom: 4vh;
  font-weight: 600;
  color: white;
  background-color: rgb(64 149 229);
  border-radius: 6px;
}
.inputcc {
  margin-bottom: 4vh;
  > span {
    display: block;
    margin-bottom: 8px;
  }
}
.zysx {
  padding: 16px;
  font-family: serif;
  font-weight: 400;
  color: black;
  background-color: rgb(212 212 212);
  border-radius: 6px;
  > span {
    display: block;
    margin-bottom: 8px;
  }
}
.zysx2 {
  font-family: serif;
  background-color: rgb(240 187 125);
  > div {
    margin-left: 1.5%;
  }
}
::v-deep .el-drawer__footer {
  > div {
    display: flex;
    justify-content: space-around;
    button {
      width: 6vw;
    }
  }
}
</style>
