<template>
  <el-row :gutter="12" class="userlist w-full h-full">
    <el-col :span="4" class="h-full overflow-auto">
      <aside class="userlist__aside">
        <el-affix
          target=".userlist__aside"
          class="userlist__aside-header"
          :offset="globalStore.assemblySize == 'small' ? 84 : 90"
        >
          <LjHeader class="flx-1" :title="$t('business.detail.basicTitle')">
            <template #toolButton>
              <el-button type="primary" text :icon="Plus" :disabled="orderStatus != ''" @click="handleAdd">{{
                $t("common.addText")
              }}</el-button>
            </template>
          </LjHeader>
          <div class="userlist__aside-searchbox">
            <el-input v-model="searchInput" size="default" clearable @input="disshow">
              <template #prefix>
                <el-icon class="el-input__icon"><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </el-affix>
        <el-empty v-if="!userListData.length" :image-size="120" description="暂无数据" />
        <!-- <LoadingCom /> -->
        <LjViewItem
          v-for="(item, index) in showUserList"
          :key="index"
          v-bind="fileClassListLayout"
          keyattr="empid"
          :current="initParams.empid"
          :data="item"
          @click-item="handleSelectItem"
        />
      </aside>
    </el-col>

    <el-col :span="20" class="h-full overflow-auto">
      <Detail
        ref="detailRef"
        :data="mainData"
        :status="orderStatus"
        @edit="handleEdit"
        @cancel="handleCancel"
        @del="handleDel"
        @goto="autoGotoUser"
        @unlock="handleUnLock"
      />
    </el-col>
  </el-row>
</template>

<script setup lang="tsx" name="saleprice_priclist">
import { ref, onMounted, provide, nextTick } from "vue";
import { getUserList, getSysFuncPwr, getDept, delUserList, UnLockUser } from "@/api/modules/basicinfo";
import { getPriceList } 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 LjViewItem from "@/components/LjViewItem/index.vue";
import variables from "@/styles/js.module.scss";
import { Files, Search, Plus } from "@element-plus/icons-vue";
import LjHeader from "@/components/LjHeader/index.vue";
import { useGlobalStore } from "@/stores/modules/global";
import { ElMessage, ElMessageBox } from "element-plus";
import { cloneDeep, pick, throttle } from "lodash-es";
import { pinyinFilterTree } from "@/utils/pinyin";

// const dwname = "web_pricelist";
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 globalStore = useGlobalStore();
const { t } = useI18n();
const { orderStatus } = useHooks();
const { CheckPower, CheckOption, buttonNew, buttonDefault } = useAuthButtons(t);
provide("orderStatus", orderStatus);

const detailRef = ref();
const headername = ref("");
const currentRow = ref<any>({});

const searchInput = ref("");
const _variables: any = variables;
const initParams = ref({
  empid: -1
});
const userListData = ref<any>([]);
const showUserList = ref<any>([]);
const userListLoading = ref(false);
provide("userListData", userListData);

const sysFuncPwrData = ref<any>([]);
provide("sysFuncPwrData", sysFuncPwrData);

const deptData = ref<any>([]);
provide("deptData", deptData);

const priceListData = ref<any>([]);
provide("priceListData", priceListData);

// const orderDefaultAction = [
//   buttonDefault({
//     label: t("common.cancelText"),
//     icon: "iconchevron-left",
//     path: "/saletask/sale/saletaskCrm/new"
//   }),
//   buttonNew({
//     label: t("common.saveText"),
//     icon: "iconsave-01",
//     path: "/saletask/sale/saletaskCrm/new"
//   })
// ];
// const orderEditAction = [
//   buttonNew({
//     label: t("common.saveText"),
//     icon: "iconsave-01",
//     path: "/saletask/sale/saletaskCrm/new"
//   })
// ];

const fileClassListLayout = ref<any>({
  header: [
    {
      value: "username",
      icon: (item: any) => {
        return item.isLocked ? <i class={["iconfont", "iconLock_light"]} /> : "";
      }
    },
    {
      value: "descrp",
      label: "描述"
    }
  ],
  aside: {
    value: "userid",
    label: "ID"
  }
});

/**
 * @description 点击列表
 */
const handleSelectItem = (data: any) => {
  let _data = cloneDeep(data);
  if (orderStatus.value) {
    ElMessageBox.confirm(t("business.detail.edittingQuit"), t("sys.app.warning"), {
      confirmButtonText: t("common.quit"),
      cancelButtonText: t("common.cancelText"),
      type: "warning"
    }).then(() => {
      handleCancel(_data);
      mainData.value = _data;
      detailRef.value.refresh(_data);
      initParams.value.empid = Number(_data.empid);
    });
    return;
  }
  console.log("handleSelectItem _data :>> ", _data);
  mainData.value = _data;
  detailRef.value.refresh(_data);
  initParams.value.empid = Number(_data.empid);
  console.log("initParams.value :>> ", initParams.value);
  // if (!Boolean(Number(data.allow_view))) {
  //   ElMessage.error("你没有权限查看");
  //   return false;
  // }
  // console.log("handleSelectItem data :>> ", data);
  // initParams.value.classid = Number(data.classid);
  // checkAllowPower(data);
};

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

const getData = async () => {
  userListLoading.value = true;
  let resSysfuncpwr = await getSysFuncPwr();
  sysFuncPwrData.value = resSysfuncpwr.list;

  let resDept = await getDept();
  deptData.value = resDept.list;

  let resPricelist = await getPriceList();
  priceListData.value = resPricelist.list;

  let res = await getUserList();
  console.log("pricelist res :>> ", res);
  userListData.value = res.userList;
  userListLoading.value = false;

  searchEvent();
};

onMounted(async () => {
  await getData();
  handleSelectItem(userListData.value[0]);
});

// const dataCallback = (data: any) => {
//   console.log("data :>> ", data);
//   return {
//     list: data.userList
//     // tableinfo: data.tableinfo,
//     // total: data.totalcnt,
//     // pageNum: data.pageindex,
//     // pageSize: data.pagesize
//   };
// };

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

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

const handleAdd = () => {
  mainData.value = {
    empid: 0,
    userid: "",
    username: "",
    descrp: "",
    usermode: 0,
    rightstring: "",
    outrepstr: "",
    deptstr: "",
    pricelist_seestr: "",
    pricelist_editstr: ""
  };

  orderStatus.value = "new";
  detailRef.value.refresh(mainData.value);
  initParams.value.empid = -1;
};

const handleEdit = (data: any) => {
  if (data.empid == 0) {
    ElMessage.error("系统管理员账号，不能修改");
    return;
  }
  orderStatus.value = "edit";
};

const handleCancel = (data?: any) => {
  let _data = data ?? mainData.value;

  console.log("_data :>> ", _data, mainData.value);
  orderStatus.value = "";

  detailRef.value.refresh(_data);
};

const handleDel = (data: any) => {
  if (data.empid == 0) {
    ElMessage.error("系统管理员账号，不能删除");
    return;
  }
  ElMessageBox.confirm(t("business.detail.delConfirm") + data.username + " ?", t("sys.app.warning"), {
    confirmButtonText: t("common.delText"),
    cancelButtonText: t("common.cancelText"),
    type: "error"
  }).then(async () => {
    await delUserList({ useridList: [data.empid] });

    await getData();
    handleSelectItem(userListData.value[0]);
  });
};

const autoGotoUser = async (id: number) => {
  await getData();
  nextTick(() => {
    orderStatus.value = "";
    let item = userListData.value.find(t => t.empid == id);
    console.log("item :>> ", item);
    handleSelectItem(item);
  });
};

const searchProps = ["username", "userid"];
// 节流
const disshow = throttle((val: any) => {
  searchEvent();
}, 500);

const searchEvent = () => {
  const filterVal = String(searchInput.value).trim().toLowerCase();
  if (filterVal) {
    showUserList.value = pinyinFilterTree(filterVal, userListData.value, searchProps);
  } else {
    showUserList.value = userListData.value;
  }
};

const handleUnLock = (data: any) => {
  if (data.empid == 0) {
    ElMessage.error("系统管理员账号，不需要解锁");
    return;
  }
  ElMessageBox.confirm(`确认需要解锁用户:${data.username}?`, t("sys.app.warning"), {
    confirmButtonText: t("common.okText"),
    cancelButtonText: t("common.cancelText"),
    type: "error"
  }).then(async () => {
    await UnLockUser({ useridList: [data.empid] });

    await getData();
    handleSelectItem(userListData.value[0]);
  });
};
</script>

<style lang="scss">
.userlist {
  &__aside {
    background: $color-gray-1;
    padding: $space-b2 $space-b2;
    box-shadow: $shadow-0-down;

    border-radius: $br-md;

    &-searchbox {
      // padding: $space-b2 $space-b2;
      // margin-bottom: $space-b2;
      // background-color: $color-gray-3;
      // border-radius: $space-b1;
      margin-bottom: $space-b2;

      .el-form-item--default:last-child {
        margin-bottom: 0;
      }
      .el-input__wrapper {
        display: flex;
      }
    }

    &-header .el-affix--fixed {
      background: $color-gray-1;
      padding-top: 12px;
      // padding-bottom: $space-b2;
    }
  }
}
</style>
