<template>
  <transition name="fade-slide">
    <LjDetail
      name="custCrmDetail"
      v-show="ifShow"
      v-if="ifInit"
      ref="LjDetailRef"
      v-bind="detailProps"
      v-model:order-status="orderStatus"
      :data="mainData"
      :init-param="mainData[0]"
      :if-layout-editable="false"
      :if-basic-editable="false"
      :if-fold-layout="false"
      :search-col="{ xs: 2, sm: 2, md: 2, lg: 2, xl: 2 }"
      :basic-group-col="{ xs: 2, sm: 2, md: 2, lg: 2, xl: 2 }"
      :action="orderStatus ? orderEditAction : orderDefaultAction"
    >
      <template #baseSetting>
        <el-row class="w-full h-full basic-inner__body" :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8" class="h-full overflow-auto">
            <div class="flx-col">
              <LjHeader class="flx-shrink" size="small" :title="$t('business.detail.syspwr')">
                <template #title>
                  <div class="flx">
                    <span>{{ $t("business.detail.syspwr") }}</span>
                    <el-input
                      ref="filterInputRef"
                      v-model="filterText"
                      class="flx-1 ml-12 mr-12"
                      clearable
                      title="支持拼音、首字母，检索名称、funcid"
                      placeholder="支持拼音、首字母，检索名称、funcid"
                    ></el-input>
                  </div>
                  <!-- <el-button :icon="!ifSearch ? Search : Close" circle @click.stop="searchCompany" /> -->
                </template>
                <template #toolButton>
                  <el-checkbox v-model="ifAllFuncpwr" :indeterminate="isIndeterminate" @change="handleSelectAllFuncpwr">{{
                    $t("common.table.selectAll")
                  }}</el-checkbox>
                </template>
              </LjHeader>
              <div class="flx-1">
                <el-tree
                  ref="sysFuncPwrTreeRef"
                  :data="sysFuncPwrData"
                  :props="defaultProps_sysfunc"
                  show-checkbox
                  node-key="funcid"
                  default-expand-all
                  :default-checked-keys="defaultCheckedKeys_sysfunc"
                  :expand-on-click-node="false"
                  check-on-click-node
                  :filter-node-method="filterNode"
                  @check-change="autoCheckSysFuncPwr"
                >
                </el-tree>
              </div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8" class="h-full overflow-auto">
            <LjHeader class="flx-1" size="small" :title="$t('business.detail.outrep')" />
            <!-- <el-tree
            ref="outrepRef"
            :data="userListData"
            :props="defaultProps_outrep"
            show-checkbox
            node-key="empid"
            default-expand-all
            :default-checked-keys="defaultCheckedKeys_outrep"
            :expand-on-click-node="false"
            check-on-click-node
          >
          </el-tree> -->

            <LjVxeTable
              ref="outrepRef"
              row-key="key"
              table-cls="flx-1"
              :data="userListData"
              :columns="columns_outrep"
              :table-props="tableProps"
              :tool-button="[]"
              :request-auto="false"
            >
            </LjVxeTable>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8" class="h-full overflow-auto">
            <div class="flx-col h-full">
              <div class="flx-1 mb-12">
                <LjHeader size="small" :title="$t('business.detail.dept')" />
                <!-- <el-tree
                ref="deptRef"
                :data="deptData"
                :props="defaultProps_dept"
                show-checkbox
                node-key="deptid"
                default-expand-all
                :default-checked-keys="defaultCheckedKeys_dept"
                :expand-on-click-node="false"
                check-on-click-node
              >
              </el-tree> -->

                <LjVxeTable
                  ref="deptRef"
                  row-key="key"
                  table-cls="flx-1"
                  :data="deptData"
                  :columns="columns_dept"
                  :table-props="tableProps"
                  :tool-button="[]"
                  :request-auto="false"
                >
                </LjVxeTable>
              </div>
              <div class="flx-1">
                <LjHeader size="small" :title="$t('business.detail.priceList')" />
                <LjVxeTable
                  ref="pricelistRef"
                  row-key="key"
                  table-cls=""
                  :data="defaultCheckedKeys_pricelist"
                  :columns="columns_pricelist"
                  :table-props="tableProps"
                  :table-events="tableEvents"
                  :tool-button="[]"
                  :request-auto="false"
                >
                  <!-- <template #edit> 321 </template> -->
                </LjVxeTable>
              </div>
            </div>
          </el-col>
        </el-row>
      </template>
    </LjDetail></transition
  >
</template>

<script setup lang="tsx" name="userDetail">
import { ref, watch, reactive, inject, nextTick, computed } from "vue";
import { DwnameEnum } from "@/enums/dwnameEnum";
import LjDetail from "@/components/LjDetail/index.vue";
import { DetailProp } from "@/components/LjDetail/interface";
import { useI18n } from "vue-i18n";
import { useHooks } from "./hooks/index";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import LjHeader from "@/components/LjHeader/index.vue";
import LjVxeTable from "@/components/LjVxeTable/index.vue";
import { cloneDeep } from "lodash-es";
import { ElMessage, ElNotification } from "element-plus";
import { saveUserList, delUserList } from "@/api/modules/basicinfo";
// import { Search, Close } from "@element-plus/icons-vue";
import { pinyinFilter } from "@/utils/pinyin";

interface detailProp {
  /**
   * @argument any 页面数据
   */
  data?: any;
  /**
   * @argument string 请求数据的api ==> 非必传
   */
  requestApi?: (params: any) => Promise<any>;
  /**
   * @argument any 基础信息，表格展示数据
   */
  // columns?: any;
  /**
   * @description 是否可编辑
   */
  status: "edit" | "new" | string;
}

const props = withDefaults(defineProps<detailProp>(), {});
const { t } = useI18n();
const { columns, columns_pricelist, columns_dept, columns_outrep } = useHooks();
const { CheckPower, CheckOption, buttonNew, buttonDefault } = useAuthButtons(t);

const mainData = ref([{}]);
const defaultCheckedKeys_sysfunc = ref([]);
const defaultCheckedKeys_outrep = ref([]);
const defaultCheckedKeys_dept = ref([]);
const defaultCheckedKeys_pricelist = ref([]);
const selected_pricelist_view = ref([]);
const selected_pricelist_edit = ref([]);

const ifShow = ref(true);
const ifInit = ref(true);
const ifAllFuncpwr = ref(true);
const isIndeterminate = ref(false);

const defaultProps_sysfunc = {
  children: "children",
  label: "menuname"
};
const defaultProps_outrep = {
  label: "username"
};
const defaultProps_dept = {
  label: "deptname"
};
const sysFuncPwrTreeRef = ref();
const outrepRef = ref();
const deptRef = ref();
const pricelistRef = ref();
const LjDetailRef = ref();
const sysFuncPwrData = inject("sysFuncPwrData", ref([]));
const deptData = inject("deptData", ref([]));
const priceListData = inject("priceListData", ref([]));
const userListData = inject("userListData", ref([]));

const emit = defineEmits(["edit", "del", "cancel", "goto", "unlock"]);

/**
 * @description 是否可编辑
 */
const orderStatus = ref("");

const orderDefaultAction = [
  buttonDefault({
    label: t("common.redo"),
    icon: "iconRefresh_light",
    clickFunc: () => {
      refresh(mainData.value[0]);
      ElMessage.success(t("sys.api.operationSuccess"));
    }
  }),
  buttonDefault({
    label: t("common.editText"),
    icon: "iconuser-edit",
    clickFunc: () => {
      if (!CheckPower(122)) {
        return "你没有【用户权限】的使用权限";
      }
      // refresh(mainData.value[0]);

      emit("edit", mainData.value[0]);
    }
  }),
  buttonDefault({
    label: t("common.delText"),
    icon: "iconwrong_light",
    clickFunc: () => {
      if (!CheckPower(122)) {
        return "你没有【用户权限】的使用权限";
      }

      emit("del", mainData.value[0]);
    }
  }),
  buttonDefault({
    label: "解锁",
    icon: "iconUnlock_light",
    clickFunc: () => {
      emit("unlock", mainData.value[0]);
    },
    limited: () => {
      return !mainData.value[0].isLocked;
    }
  })
];

const orderEditAction = [
  buttonDefault({
    label: t("common.cancelText"),
    icon: "iconchevron-left",
    clickFunc: () => {
      emit("cancel");
    }
  }),
  buttonNew({
    label: t("common.saveText"),
    icon: "iconsave-01",
    clickFunc: async () => {
      let ls_rightstring = Array(1000).fill("0").join("");
      let ls_outrepstr = "-1";
      let ls_deptstr = "-1";
      let ls_pricelist_seestr = "-1";
      let ls_pricelist_editstr = "-1";

      /** 权限值 */
      let current: any = sysFuncPwrTreeRef.value.getCheckedKeys();
      current.forEach(index => {
        if (index > 0 && index <= 1000) {
          ls_rightstring = ls_rightstring.substring(0, index - 1) + "1" + ls_rightstring.substring(index);
        }
      });

      /** 业务员 */
      let ifAllOutrep = outrepRef.value.element.isAllCheckboxChecked();
      if (!ifAllOutrep) {
        let selected = outrepRef.value.element.getCheckboxRecords(true);
        let selectedName = selected.map((item: any) => item.username).join(",");
        if (selectedName.length > 0) {
          ls_outrepstr = "," + selectedName + ",";
        } else {
          ls_outrepstr = "0";
        }
      }

      /** 部门 */
      let ifAllDept = deptRef.value.element.isAllCheckboxChecked();
      if (!ifAllDept) {
        let selected = deptRef.value.element.getCheckboxRecords(true);
        let selectedName = selected.map((item: any) => item.deptid).join(",");
        if (selectedName.length > 0) {
          ls_deptstr = "," + selectedName + ",";
        } else {
          ls_deptstr = "0";
        }
      }
      console.log("ls_deptstr :>> ", ls_deptstr);

      /** 价格表 */
      console.log("defaultCheckedKeys_pricelist.value :>> ", defaultCheckedKeys_pricelist.value);
      let selected_view = defaultCheckedKeys_pricelist.value.filter(t => t.view);
      if (!selected_view.length) {
        ls_pricelist_seestr = "0";
      } else if (selected_view.length < defaultCheckedKeys_pricelist.value.length) {
        ls_pricelist_seestr = "," + selected_view.map(t => t.pricelistid).join(",") + ",";
      }
      let selected_edit = defaultCheckedKeys_pricelist.value.filter(t => t.edit);
      if (!selected_edit.length) {
        ls_pricelist_editstr = "0";
      } else if (selected_edit.length < defaultCheckedKeys_pricelist.value.length) {
        ls_pricelist_editstr = "," + selected_edit.map(t => t.pricelistid).join(",") + ",";
      }
      console.log("ls_pricelist_seestr :>> ", ls_pricelist_seestr);
      console.log("ls_pricelist_editstr :>> ", ls_pricelist_editstr);

      console.log("mainData.value :>> ", mainData.value);
      console.log("LjDetailRef :>> ", LjDetailRef.value.infoParam);

      const initParams = LjDetailRef.value?._mainData;
      console.log("initParams :>> ", initParams);
      let res = await saveUserList({
        userList: [
          {
            ...initParams,
            rightstring: ls_rightstring,
            outrepstr: ls_outrepstr,
            deptstr: ls_deptstr,
            pricelist_seestr: ls_pricelist_seestr,
            pricelist_editstr: ls_pricelist_editstr
          }
        ]
      });
      console.log("saveUserList res :>> ", res);
      if (res) {
        if (initParams.empid == 0) {
          ElNotification({
            title: t("sys.api.operationSuccess"),
            message: t("business.detail.successToAdd"),
            type: "success"
          });
        } else {
          ElNotification({
            title: t("sys.api.operationSuccess"),
            message: t("business.detail.successToEdit"),
            type: "success"
          });
        }
        emit("goto", res.empid);
      }
    }
  })
];

const detailProps = reactive<DetailProp>({
  dwname: DwnameEnum.userlist,
  columns: columns,
  // detailApi: {
  //   requestApi: getDetailData,
  //   initParam: initParam.value
  // },
  header: {
    fieldNames: {
      code: "cuscode",
      codeLabel: t("table.u_cust.cuscode") + "：",
      name: "name"
    },
    icon: "iconuser-01",
    // icon: Close
    // icon: (params: any) => {
    //   console.log("detailProps params :>> ", params);
    //   return <i class={"iconfont iconclipboard-check"}></i>;
    // }
    tabsProp: {
      scrollspy: false,
      sticky: true
    }
  },
  mould: [
    {
      id: "baseSetting",
      type: "table",
      label: t("business.detail.basicSetting")
    }
  ]
});

/**
 * @description 提取出所有的 funcid
 * @param data
 */
const extractFuncIds = (data: any) => {
  let funcIds = [];

  data.forEach(item => {
    // 添加当前项的 funcid
    funcIds.push(item.funcid);

    // 如果当前项有子项，则递归处理子项
    if (item.children && Array.isArray(item.children)) {
      funcIds = funcIds.concat(extractFuncIds(item.children));
    }
  });

  return funcIds;
};

const allFuncpwrid = computed(() => {
  return extractFuncIds(sysFuncPwrData.value);
});

const autoCheckSysFuncPwr = (data: any) => {
  let current: any = sysFuncPwrTreeRef.value.getCheckedKeys();
  ifAllFuncpwr.value = allFuncpwrid.value.length == current.length;
  isIndeterminate.value = current.length > 0 && allFuncpwrid.value.length > current.length;
};

const handleSelectAllFuncpwr = (val: boolean) => {
  defaultCheckedKeys_sysfunc.value = val ? allFuncpwrid.value : [];
  sysFuncPwrTreeRef.value.setCheckedKeys(defaultCheckedKeys_sysfunc.value, true);
  // ifAllFuncpwr.value = val;
  isIndeterminate.value = false;
};

const refresh = (val: any) => {
  mainData.value = [val];
  /* 权限值 */
  if (val.empid == 0 && val.userid) {
    defaultCheckedKeys_sysfunc.value = allFuncpwrid.value;
  } else {
    defaultCheckedKeys_sysfunc.value = val.rightstring
      .split("")
      .map((t, idx) => Number(t) > 0 && idx + 1)
      .filter(t => t);
  }
  ifAllFuncpwr.value = allFuncpwrid.value.length == defaultCheckedKeys_sysfunc.value.length;
  isIndeterminate.value =
    defaultCheckedKeys_sysfunc.value.length > 0 && allFuncpwrid.value.length > defaultCheckedKeys_sysfunc.value.length;
  sysFuncPwrTreeRef.value.setCheckedKeys(defaultCheckedKeys_sysfunc.value, true);

  /* 业务员 */
  // if (val.outrepstr == "-1") {
  //   // -1： 全选
  //   defaultCheckedKeys_outrep.value = userListData.value.map(t => t.empid);
  // } else if (val.outrepstr == "0") {
  //   // 0： 全不选
  //   defaultCheckedKeys_outrep.value = [];
  // } else {
  //   // 部分选
  //   let outrepArr = val.outrepstr.split(",").filter(t => t);
  //   defaultCheckedKeys_outrep.value = userListData.value
  //     .map(t => outrepArr.includes(t.username) && t)
  //     .filter(t => t)
  //     .map(t => t.empid);
  // }
  // outrepRef.value.setCheckedKeys(defaultCheckedKeys_outrep.value, true);
  console.log('val.outrepstr == "-1" :>> ', val.outrepstr == "-1");
  if (val.outrepstr == "-1") {
    // -1： 全选
    // defaultCheckedKeys_outrep.value = cloneDeep(userListData.value);
    defaultCheckedKeys_outrep.value = userListData.value.filter(t => t.username);
  } else if (val.outrepstr == "0") {
    // 0： 全不选
    defaultCheckedKeys_outrep.value = [];
  } else {
    // 部分选
    let outrepArr = val.outrepstr.split(",").filter(t => t);
    defaultCheckedKeys_outrep.value = userListData.value.map(t => outrepArr.includes(t.username) && t).filter(t => t);
  }
  outrepRef.value.element.clearCheckboxRow();
  outrepRef.value.element.setCheckboxRow(defaultCheckedKeys_outrep.value, true);

  /* 部门 */
  // if (val.deptstr == "-1") {
  //   // -1： 全选
  //   defaultCheckedKeys_dept.value = deptData.value.map(t => t.deptid);
  // } else if (val.deptstr == "0") {
  //   // 0： 全不选
  //   defaultCheckedKeys_dept.value = [];
  // } else {
  //   // 部分选
  //   defaultCheckedKeys_dept.value = val.deptstr
  //     .split(",")
  //     .filter(t => t)
  //     .map(t => Number(t));
  // }
  // deptRef.value.setCheckedKeys(defaultCheckedKeys_dept.value, true);

  if (val.deptstr == "-1") {
    // -1： 全选
    defaultCheckedKeys_dept.value = deptData.value.filter(t => t.deptid);
  } else if (val.deptstr == "0") {
    // 0： 全不选
    defaultCheckedKeys_dept.value = [];
  } else {
    // 部分选
    let deptArr = val.deptstr
      .split(",")
      .filter(t => t)
      .map(t => Number(t));
    console.log("deptArr :>> ", deptArr);
    defaultCheckedKeys_dept.value = deptData.value.filter(t => deptArr.includes(t.deptid));
  }
  deptRef.value.element.clearCheckboxRow();
  deptRef.value.element.setCheckboxRow(defaultCheckedKeys_dept.value, true);

  /** 价格列表 */
  if (val.pricelist_seestr == "-1") {
    // -1： 全选
    selected_pricelist_view.value = priceListData.value.map(t => t.pricelistid);
  } else if (val.pricelist_seestr == "0") {
    // 0： 全不选
    selected_pricelist_view.value = [];
  } else {
    // 部分选
    let plArr = val.pricelist_seestr.split(",").filter(t => t);
    selected_pricelist_view.value = priceListData.value
      .map(t => plArr.includes(t.pricelistname) && t)
      .filter(t => t)
      .map(t => t.pricelistid);
  }

  if (val.pricelist_editstr == "-1") {
    // -1： 全选
    selected_pricelist_edit.value = priceListData.value.map(t => t.pricelistid);
  } else if (val.pricelist_editstr == "0") {
    // 0： 全不选
    selected_pricelist_edit.value = [];
  } else {
    // 部分选
    let plArr = val.pricelist_editstr.split(",").filter(t => t);
    selected_pricelist_edit.value = priceListData.value
      .map(t => plArr.includes(t.pricelistname) && t)
      .filter(t => t)
      .map(t => t.pricelistid);
  }
  defaultCheckedKeys_pricelist.value = cloneDeep(priceListData.value);
  defaultCheckedKeys_pricelist.value.map((item: any) => {
    item.view = selected_pricelist_view.value.includes(item.pricelistid);
    item.edit = selected_pricelist_edit.value.includes(item.pricelistid);
    return item;
  });
};

// watch(
//   () => props.data,
//   val => {
//     // ifInit.value = true;
//     // nextTick(() => {
//     //   ifShow.value = true;
//     console.log("props.data, val :>> ", val);
//     mainData.value = [val];

//     nextTick(() => {
//       refresh(val);
//     });
//     // });
//   }
//   // { immediate: true }
// );

watch(
  () => props.status,
  val => {
    console.log("props.status val :>> ", val);
    if (val != orderStatus.value) {
      ifShow.value = false;
      setTimeout(() => {
        ifInit.value = false;
        orderStatus.value = val;

        tableProps.editConfig.enabled = orderStatus.value != "";

        setTimeout(() => {
          ifInit.value = true;
          nextTick(() => {
            ifShow.value = true;
            nextTick(() => {
              refresh(props.data);
            });
          });
        }, 100);
      }, 500);
    }
  },
  { immediate: true, deep: true }
);

const handleCheckboxChange = (data: any) => {
  console.log("handleCheckboxChange data :>> ", data);
  // selected_pricelist.value = data.records;
};

const tableProps = reactive({
  height: "",
  // minHeight: "300px",
  // maxHeight: "600px",
  // cellStyle: cellStyle,
  // headerCellStyle: headerCellStyle,
  editConfig: { trigger: "click", mode: "cell", enabled: orderStatus.value != "" },
  checkboxConfig: { trigger: "row" },
  keepSource: true
  // keyboardConfig: {
  //   isChecked: true
  // }
});

const tableEvents = {
  "checkbox-change": handleCheckboxChange,
  "checkbox-range-change": handleCheckboxChange,
  "checkbox-all": handleCheckboxChange
  // "cell-dblclick": handleDBlClickTable,
  // "cell-click": handleClickTable,
  // "edit-closed": autoEditClosed
};

const ifSearch = ref(false);
const filterText = ref();
const filterInputRef = ref();

// /**
//  * @description 搜索
//  */
//  const searchCompany = () => {
//   // if (!ifSearch.value) {
//   //   ifSearch.value = true;
//     nextTick(() => {
//       filterInputRef.value.focus();
//     });
//   // } else {
//   //   ifSearch.value = false;
//   //   filterText.value = "";
//   //   sysFuncPwrTreeRef.value!.filter("");
//   // }
// };
// 关键字,筛选
watch(filterText, val => {
  sysFuncPwrTreeRef.value!.filter(val);
});

// 筛选钩子
const filterNode = (value: string, data: any, node: any) => {
  if (!value) return true;
  return partentFilter(value, data, node);
};

/**
 * 拼音筛选,父级符合,其自己,孙集均符合
 * @param value keyword
 * @param data 当前层级数据
 * @param node 节点
 */
const partentFilter = (value: string, data: any, node: any): boolean => {
  let arr = pinyinFilter(value, [data], ["treename", "menuname", "funcid"]);
  console.log("arr :>> ", arr);
  console.log("data :>> ", data);
  console.log("node.parent level :>> ", node.parent.level);
  if (arr.length > 0) {
    return true;
  } else if (node.parent.level > 0) {
    return partentFilter(value, node.parent.data, node.parent);
  } else {
    return false;
  }
};

defineExpose({
  refresh
});
</script>

<style lang="scss">
.longjoe-detail-layout.fold-vertical {
  display: flex;
  flex-direction: column;

  .longjoe-detail-layout__tabs {
    flex: 1;
    // height: unset;
    overflow: hidden;
  }
}

.basic-inner__body {
  flex: 1;

  @media screen and (max-width: $screen-md) {
    flex: unset;
  }
}
</style>
