<template>
  <div class="table-box">
    <LjVxeTable
      ref="VxeTableRef"
      row-key="deptid"
      :columns="columns"
      :request-api="getData"
      :data-callback="dataCallback"
      :init-param="initParams"
      :dwname="dwname"
      :table-props="tableProps"
      :table-events="tableEvents"
      :tool-button="['export', 'refresh', 'setting', 'search', 'location']"
      :auto-load-layout="false"
      pagination
    >
      <template #tableHeader>
        <el-tabs v-model="initParams.kind" class="tableheader-tabs">
          <el-tab-pane label="床网" :name="0"></el-tab-pane>
          <el-tab-pane label="床垫" :name="1"></el-tab-pane>
        </el-tabs>
      </template>
    </LjVxeTable>
  </div>

  <LjDialog
    ref="LjDrawerRef"
    class="is-selector"
    v-bind="{
      ...drawerDefineProp
    }"
    :style="{ padding: 0 }"
  >
    <template #header>
      <div class="flx-1">
        <span class="text-h5-b">部门: {{ deptname }}</span>
      </div>
    </template>
    <div class="flx-1 h-full">
      <LjHeaderMenu :data="mainData" :action="orderStatus ? orderEditAction : orderDefaultAction" />
      <Detail class="flx-1" :data="mainData" :status="orderStatus" :enum="enumMap" />
    </div>
  </LjDialog>
</template>

<script setup lang="ts" name="saleprice_profitratelist">
import { ref, onMounted, provide } from "vue";
import { getProfitRateList } from "@/api/modules/saleprice";
import { ColumnProps } from "@/components/LjVxeTable/interface";
import LjDrawer from "@/components/LjDrawer/index.vue";
import Detail from "./detail.vue";
import { useHooks } from "./hooks/index";
import LjDialog from "@/components/LjDialog/index.vue";
import LjHeaderMenu from "@/components/LjHeaderMenu/index.vue";
import { useI18n } from "vue-i18n";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { ALLOW_EDIT_STATE } from "@/config/index";
import { cloneDeep } from "lodash-es";

const dwname = "web_profitratelist";
const mainData = ref({});
const tableProps = {
  height: "auto",
  editConfig: { trigger: "click", mode: "cell" }
  // rowClassName: rowClsNameFunc
  // exportConfig: {
  //   filename: t("menu.saletaskmx") + formatToDate(new Date(), "YYYY-MM-DD HH:mm:ss")
  // }
};

const { t } = useI18n();
const { VxeTableRef, LjDetailRef, columns, fSave } = useHooks(t);
const { CheckPower, CheckOption, buttonNew, buttonDefault } = useAuthButtons(t);

const initParams = ref({ kind: 0 });
const orderStatus = ref("");
const deptname = ref("");
const enumMap = ref(new Map());

const orderDefaultAction = [
  buttonDefault({
    label: t("common.cancelText"),
    icon: "iconchevron-left"
  }),
  buttonNew({
    label: t("common.saveText"),
    icon: "iconsave-01",
    clickFunc: item => {
      // fSaveDept({ dept: LjDetailRef.value?.infoParam }).then(() => {
      //   LjDrawerRef.value.hide();
      // });
    }
  })
];
const orderEditAction = [
  buttonNew({
    label: t("common.saveText"),
    icon: "iconsave-01",
    clickFunc: item => {
      const save_data = LjDetailRef.value?._mainData;
      // 重组数据
      const list = [];
      for (let key in save_data) {
        if (key.indexOf("profitrate_") > -1) {
          list.push({
            deptid: save_data.deptid,
            bednet_or_mattress: initParams.value.kind,
            bednettypeid_mattresstypeid: parseInt(save_data[key.replace("profitrate", "bednettype")]),
            profitrate: save_data[key]
          });
        }
      }

      fSave({ list }).then(() => {
        LjDrawerRef.value.hide();
      });
    }
  })
];

/*
 * @description 抽屉默认属性
 */
const drawerDefineProp = {
  draggable: true,
  overflow: true,
  width: "40%"
  // modalClass: "lj-file-dialog"
};

const getData = (params: any) => {
  return getProfitRateList(params);
};

const dataCallback = (data: any) => {
  let deptSet = new Map();
  let bednetMap = new Map();

  if (data.datatable?.length > 0) {
    data.datatable?.forEach((item: any) => {
      deptSet.has(item.deptid) || deptSet.set(item.deptid, {});
      bednetMap.has(item.bednettypeid_mattresstypeid) || bednetMap.set(item.bednettypeid_mattresstypeid, item.typename);

      let obj = deptSet.get(item.deptid);

      Reflect.set(obj, "deptid", parseInt(item.deptid));
      Reflect.set(obj, "deptname", item.deptname);
      Reflect.set(obj, `bednettype_${item.bednettypeid_mattresstypeid}`, item.bednettypeid_mattresstypeid);
      Reflect.set(obj, `profitrate_${item.bednettypeid_mattresstypeid}`, item.profitrate);
    });
  }

  let datatable = Array.from(deptSet.values());

  columns.length = 0;

  columns.push({
    type: "seq",
    title: "#",
    fixed: "left",
    width: 80
  });

  columns.push({
    field: "deptname",
    title: "部门",
    basicinfo: {
      el: "input",
      span: 2,
      editable: ALLOW_EDIT_STATE,
      props: {
        readonly: true
      }
    }
  });

  for (let item of bednetMap) {
    columns.push({
      field: `profitrate_${item[0]}`,
      title: item[1],
      width: 0,
      basicinfo: {
        el: "input",
        span: 2,
        editable: ALLOW_EDIT_STATE,
        props: {
          placeholder: "请输入利润率"
        },
        rules: [{ required: true, message: "汇率不能为0", trigger: "change" }]
      }
    });
  }

  // if (data.tableinfo?.columns) {
  //   data.tableinfo?.columns.map((item: any) => {
  //     if (item?.enum) {
  //       enumMap.value.set(item.field, item.enum);
  //     }
  //   });
  // }
  return {
    list: datatable,
    tableinfo: [],
    total: data.totalcnt,
    pageNum: data.pageindex,
    pageSize: data.pagesize
  };
};

const LjDrawerRef = ref();
const handleDBlClickTable = ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }: any) => {
  // 弹窗
  mainData.value = cloneDeep(row);
  deptname.value = row.deptname;
  orderStatus.value = "edit";
  LjDrawerRef.value.show();
};

// 返回绑定的事件
const tableEvents = {
  "cell-dblclick": handleDBlClickTable
  // "cell-click": handleClickTable
};
</script>
