<template>
  <div class="flx-col h-full">
    <div class="main-box">
      <LjFoldLayout ref="LjFoldLayoutRef" v-bind="layoutSetting" :dwname="dwname">
        <template #left>
          <div class="flx-col h-full card">
            <van-tabs v-model:active="initParams.arg_typeid" @click-tab="gMattressExtraTypeList">
              <van-tab title="特殊工艺" :name="1"></van-tab>
              <van-tab title="材料额外费用" :name="2"></van-tab>

              <template #nav-right v-if="CheckPower(130)">
                <div class="flx-center">
                  <el-button :icon="Plus" circle ref="addBtnRef" @click="openTypePopover" />
                </div>
              </template>
            </van-tabs>
            <TreeFilter
              ref="LjTreeRef"
              id="extraid"
              wrapper-cls=""
              label="typename"
              :searchable="false"
              :expand-on-click-node="true"
              :data="extraTypeList"
              @change="changeTreeFilter"
            >
              <template #default="{ node }">
                <div class="flx-justify-between flx-1">
                  <span class="title">{{ node.label }}</span>
                  <el-space class="mr-4" v-if="node.data.extraid && CheckPower(130)">
                    <el-button
                      :ref="el => setDynamicRef(el, `buttonRefs_` + node.data.extraid)"
                      :icon="EditPen"
                      circle
                      size="small"
                      @click="handleEditType(node, `buttonRefs_` + node.data.extraid)"
                    />
                    <el-button
                      :ref="el => setDynamicRef(el, `buttonRefs_del_` + node.data.extraid)"
                      :icon="Delete"
                      type="danger"
                      plain
                      circle
                      size="small"
                      @click="handleDeleteType(node, `buttonRefs_del_` + node.data.extraid)"
                    />
                  </el-space>
                </div>
              </template>
            </TreeFilter>
          </div>
        </template>
        <div class="main-box flx-col">
          <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-button-group class="mt-12">
                <el-button @click="handleOpenNewTable">{{ $t("common.add") }}</el-button>
                <el-button @click="fDelete">{{ $t("common.delText") }}</el-button>
              </el-button-group>
            </template>
          </LjVxeTable>
        </div>
      </LjFoldLayout>
    </div>
  </div>

  <LjPopover ref="LjPopoverRef" :title="popoverTitle" width="320">
    <template v-if="!ifdel">
      <!-- <p>{{ popoverTitle }}</p> -->
      <div class="mb-8">
        <el-input v-model="typeItem.typename" placeholder="请输入类型名称"></el-input>
      </div>
      <div class="mb-8">
        <span>录入类型： </span>
        <!-- <el-select v-model="typeItem.inputtype" style="width: 120px">
          <el-option label="仅可选择" :value="0"></el-option>
          <el-option label="选择且可录入" :value="1"></el-option>
        </el-select> -->
        <el-segmented v-model="typeItem.inputtype" :options="inputtypeOptions" size="small" />
      </div>
      <div style="display: flex; text-align: right; margin: 0">
        <el-button class="flx-1" size="small" type="primary" @click="gotoSaveType">保存</el-button>
      </div>
    </template>
    <template v-else>
      <p>如有单据选择此类型，将无法显示项目类型</p>
      <div style="display: flex; text-align: right; margin: 0">
        <el-button class="flx-1" size="small" type="danger" @click="gotoDelType">删除</el-button>
      </div>
    </template>
  </LjPopover>

  <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="orderEditAction" />
      <Detail class="flx-1" :data="mainData" :status="orderStatus" :enum="enumMap" />
    </div>
  </LjDialog>
</template>

<script setup lang="ts" name="baseinfo_mattress_extralist">
import { ref, onMounted, provide, computed, unref, reactive } from "vue";
import { getMattressExtraList, SaveMattressExtraType, DeleteMattressExtraType } from "@/api/modules/basicinfo";
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";
import { CommonDynamicSelect } from "@/api/modules/common";
import { Select, Plus, EditPen, Delete } from "@element-plus/icons-vue";
import { ElNotification, ClickOutside as vClickOutside } from "element-plus";
import { DwnameEnum } from "@/enums/dwnameEnum";
import LjPopover from "@/components/LjPopover/index.vue";
import { useDynameicRef } from "@/hooks/useDynameicRef";

const dwname = "web_extra_costs";
const mainData = ref({});

const layoutSetting = {
  dwname: dwname,
  right: {
    hidden: true
  }
};
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 inputtypeOptions = [
  {
    label: "仅可选择",
    value: 0
  },
  {
    label: "选择且可录入",
    value: 1
  },
  {
    label: "不可修改",
    value: 2
  }
];

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

const initParams = ref<any>({ arg_typeid: 1 });
const orderStatus = ref("");
const deptname = ref("");
const enumMap = ref(new Map());
const extraTypeList = ref<any>([]);

const LjPopoverRef = ref();
const LjTreeRef = ref();
const addBtnRef = ref();
const ifdel = ref(false);

const buttonRefs = ref();
const type_visible = ref(false);
const type_name = ref("");
const typeItem = ref<any>({
  extraid: 0,
  typename: "",
  typeid: 0,
  inputtype: 0
});

const popoverTitle = computed(() => {
  if (ifdel.value) {
    return "删除" + (initParams.value.arg_typeid === 1 ? "特殊工艺类型" : "材料额外费用类型");
  }
  return (
    (typeItem.value.extraid === 0 ? "新增" : "修改") + (initParams.value.arg_typeid === 1 ? "特殊工艺类型" : "材料额外费用类型")
  );
});

const openTypePopover = (refName: string) => {
  ifdel.value = false;
  typeItem.value.extraid = 0;
  typeItem.value.typeid = initParams.value.arg_typeid;
  typeItem.value.typename = "";
  typeItem.value.inputtype = 0;

  LjPopoverRef.value.show(addBtnRef.value);
};

const gotoSaveType = async () => {
  if (!typeItem.value.typename.trim()) {
    ElMessage.warning("请输入类型名称");
    return false;
  }

  typeItem.value.typeid = initParams.value.arg_typeid;
  typeItem.value.typename = typeItem.value.typename.trim();

  let res = await SaveMattressExtraType({ data: typeItem.value });

  if (res.ErrMsg) {
    ElNotification({
      title: "保存失败",
      message: res.ErrMsg,
      type: "error"
    });
    return false;
  } else {
    ElNotification({
      title: "温馨提示",
      message: "保存成功！",
      type: "success"
    });
    gMattressExtraTypeList();

    LjPopoverRef.value.close();
  }

  type_visible.value = false;
};

const handleEditType = (node: any, refName: string) => {
  ifdel.value = false;
  console.log("handleEditType :>> ", node);
  console.log("handleEditType dynamicRefs.value[refName]:>> ", dynamicRefs.value[refName]);
  typeItem.value.extraid = node.data.extraid;
  typeItem.value.typeid = initParams.value.arg_typeid;
  typeItem.value.typename = node.data.typename;
  typeItem.value.inputtype = node.data.inputtype;

  LjPopoverRef.value.show(dynamicRefs.value[refName]);
};

const gotoDelType = async () => {
  typeItem.value.typeid = initParams.value.arg_typeid;

  let res = await DeleteMattressExtraType({ list: [typeItem.value] });

  if (res.ErrMsg) {
    ElNotification({
      title: "删除失败",
      message: res.ErrMsg,
      type: "error"
    });
    return false;
  } else {
    ElNotification({
      title: "温馨提示",
      message: "删除成功！",
      type: "success"
    });
    gMattressExtraTypeList();

    LjPopoverRef.value.close();
  }
};

const handleDeleteType = (node: any, refName: string) => {
  ifdel.value = true;
  console.log("handleDeleteType :>> ", node);
  typeItem.value.extraid = node.data.extraid;
  typeItem.value.typeid = initParams.value.arg_typeid;

  LjPopoverRef.value.show(dynamicRefs.value[refName]);
};

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 => {
      let save_data = LjDetailRef.value?._mainData;
      save_data.inuse = Number(save_data.inuse);
      save_data.ifinit = Number(save_data.ifinit);

      fSave({ data: save_data }).then(() => {
        LjDrawerRef.value.hide();
      });
    }
  }),
  buttonDefault({
    label: t("common.delText"),
    clickFunc: item => {
      let save_data = LjDetailRef.value?._mainData;

      fDelete({ list: [save_data] }).then(() => {
        LjDrawerRef.value.hide();
      });
    }
  })
];

const gMattressExtraTypeList = async () => {
  // console.log("getData_subSpecs getData params :>> ", params);
  let newParams: any = {};
  // params.pageNum && (newParams.pageindex = params.pageNum);
  // params.pageSize && (newParams.pagesize = params.pageSize);
  // delete params.pageNum;
  // delete params.pageSize;
  newParams.queryParams = {
    arg_typeid: initParams.value.arg_typeid
  };
  // console.log("params :>> ", params);
  newParams.dsname = "_Mapper_mattressextra";
  let res = await CommonDynamicSelect(newParams, DwnameEnum.mattressExtraType);

  extraTypeList.value = res.datatable;

  // let enumArr = res.datatable.map((item: any) => {
  //   return {
  //     label: item.typename,
  //     value: item.extraid
  //   };
  // });
  // enumMap.value.set("extraid", enumArr);
};

const changeTreeFilter = (val: number) => {
  console.log("changeTreeFilter val :>> ", val);
  initParams.value.arg_extraid = val?.extraid ?? 0;
};

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

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

const dataCallback = (data: any) => {
  data.tableinfo?.columns.map((item: any) => {
    if (item?.field === "inputtype") {
      let enumArr = item.enum.filter(item => item.value !== 0);
      enumMap.value.set(item.field, enumArr);
    } else if (item?.enum) {
      enumMap.value.set(item.field, item.enum);
    }
  });

  return {
    list: data.datatable,
    tableinfo: data.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 handleOpenNewTable = () => {
  mainData.value = {
    extraid: initParams.value.arg_extraid,
    extramxid: 0,
    typeid: initParams.value.arg_typeid,
    inputtype: 1
  };
  console.log(Number(initParams.value.arg_typeid) == 1);
  // typename.value = "";
  deptname.value = "新增" + (Number(initParams.value.arg_typeid) == 1 ? "特殊工艺" : "额外费用");
  orderStatus.value = "new";
  LjDrawerRef.value.show();
};

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

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

<style lang="scss">
.el-tree-node.is-current {
  .el-tree-node__content {
    .title {
      color: var(--lj-color-background);
    }
  }
}
</style>
