<template>
  <LjSelector
    ref="LjSelectorRef"
    :title="$t('business.selector.saletask.title')"
    v-model:value="selectList"
    :action="action"
    v-bind="$attrs"
    :item-layout="selectedLayout"
    :item-key="TABLE_KEY"
    :multipleLimit="0"
    :before-submit="beforeSubmit"
    @change-value="autoUpdateTableCheckbox"
  >
    <template #aside>
      <el-collapse-item name="mtrl">
        <template #title>
          {{ $t("common.table.searchBtn") }}
          <el-icon class="ml-4"><Search /></el-icon>
        </template>
        <el-form v-model="initParams" class="pl-4">
          <el-form-item :label="$t('business.selector.saletask.keyword')">
            <template #label>
              <div class="flx-center">
                <span>
                  {{ $t("business.selector.saletask.keyword") }}
                </span>
                <el-tooltip :content="$t('business.selector.saletask.keywordTips')">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <el-input
              v-model.trim="keyword"
              :title="$t('business.selector.saletask.keyword')"
              :placeholder="$t('business.selector.saletask.keywordTips')"
              @input="disshow(keyword)"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('table.u_mtrldef.mtrlorigin')">
            <el-select
              v-model="initParams.mtrlorigin"
              clearable
              :placeholder="$t('common.all') + $t('table.u_mtrldef.mtrlorigin')"
              :title="$t('table.u_mtrldef.mtrlorigin')"
            >
              <el-option v-for="item in mtrloriginOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('table.u_mtrldef.mtrlprp')">
            <el-select
              v-model="initParams.mtrlprp"
              clearable
              :placeholder="$t('common.all') + $t('table.u_mtrldef.mtrlprp')"
              :title="$t('table.u_mtrldef.mtrlprp')"
            >
              <el-option v-for="item in mtrlprpOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('table.u_mtrldef.mtrltype')">
            <!-- <el-cascader :props="mtrlTypeProps" /> -->
            <CascaderFilter
              v-model:value="initParams.mtrltypeid"
              label="text"
              :request-api="getMtrltype"
              filterable
              @change="changeTreeFilter"
            />
          </el-form-item>
          <el-form-item :label="$t('business.selector.saletask.ifpack')">
            <!-- <el-checkbox v-model="initParams.ifpack" :label="$t('business.selector.saletask.ifpack')" name="ifpack"></el-checkbox> -->
            <el-switch v-model="initParams.ifpack" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
        </el-form>
      </el-collapse-item>
    </template>
    <template #default>
      <van-tabs v-model:active="activeTable" class="lj-van-tabs-flex-full" shrink @change="handleTabsClick">
        <van-tab :title="$t('business.selector.saletask.mtrldef')" name="mtrldef">
          <MtrlTable
            ref="mtrldefRef"
            :tab-active="activeTable == activeTableLast"
            v-model:params="initParams"
            v-model:selected="selectList"
            :table-props="tableProps"
            :cell-click="handleCellClick"
            :param-attr="paramsAttrs"
            @change="autoSelectedChange"
          />
        </van-tab>
        <van-tab :title="$t('business.selector.saletask.cust')" name="cust">
          <CusTable
            ref="cusRef"
            :tab-active="activeTable == activeTableLast"
            v-model:params="initParams"
            :selected="selectList"
            :table-props="tableProps"
            :cell-click="handleCellClick"
            :param-attr="paramsAttrs"
            @change="autoSelectedChange"
          />
        </van-tab>
        <van-tab :title="$t('business.selector.saletask.history')" name="history">
          <HistoryTable
            ref="historyRef"
            :tab-active="activeTable == activeTableLast"
            v-model:params="initParams"
            v-model:selected="selectList"
            :table-props="tableProps"
            :cell-click="handleCellClick"
            :param-attr="paramsAttrs"
            @change="autoSelectedChange"
          />
        </van-tab>
        <van-tab :title="$t('business.selector.saletask.mtrlware')" name="mtrlware">
          <MtrlwareTable
            ref="mtrlwareRef"
            :tab-active="activeTable == activeTableLast"
            v-model:params="initParams"
            :selected="selectList"
            :table-props="tableProps"
            :cell-click="handleCellClick"
            :param-attr="paramsAttrs"
            @change="autoSelectedChange"
          />
        </van-tab>
        <van-tab :title="$t('business.selector.saletask.price')" name="price">
          <PriceTable
            ref="priceRef"
            :tab-active="activeTable == activeTableLast"
            v-model:params="initParams"
            :selected="selectList"
            :table-props="tableProps"
            :cell-click="handleCellClick"
            :param-attr="paramsAttrs"
            @change="autoSelectedChange"
          />
        </van-tab>
        <!-- <template #nav-right>
          <div class="flx-end flx-1">
            <el-space>
              <el-select
                v-model="initParams.mtrlorigin"
                clearable
                :placeholder="$t('common.all') + $t('table.u_mtrldef.mtrlorigin')"
                :title="$t('table.u_mtrldef.mtrlorigin')"
                style="width: 130px"
              >
                <el-option v-for="item in mtrloriginOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-input
                v-model.trim="keyword"
                :title="$t('business.selector.saletask.keyword')"
                :placeholder="$t('business.selector.saletask.keyword')"
                style="width: 160px"
                @input="disshow(keyword)"
              ></el-input>
              <el-checkbox
                v-model="initParams.ifpack"
                :label="$t('business.selector.saletask.ifpack')"
                name="ifpack"
              ></el-checkbox>
              <el-select
                v-model="initParams.mtrlprp"
                clearable
                :placeholder="$t('common.all') + $t('table.u_mtrldef.mtrlprp')"
                :title="$t('table.u_mtrldef.mtrlprp')"
                style="width: 130px"
              >
                <el-option v-for="item in mtrlprpOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-space>
          </div>
        </template> -->
      </van-tabs>
    </template>
  </LjSelector>
</template>

<script lang="tsx" setup name="SelectorMtrlwareSaletaskDialog">
import { reactive, toRefs, ref, onMounted, nextTick, inject, watch, computed } from "vue";
// import LjDialog from "@/components/LjDialog/index.vue";
// import LjFoldLayoutDouble from "@/components/LjFoldLayoutDouble/index.vue";
import LjVxeTable from "@/components/LjVxeTable/index.vue";
// 注意: 需要按需引入使用到的第三方UI组件
// import { ElDialog, ElButton } from "element-plus";
import { QuestionFilled, Search } from "@element-plus/icons-vue";
import type { CascaderProps } from "element-plus";

import { getL1MtrlType } from "@/api/modules/technology";
import TreeFilter from "@/components/TreeFilter/index.vue";
import CascaderFilter from "@/components/TreeFilter/cascader.vue";
// import { useCust } from "@/views/saletask/cust/hooks/index";
import { useI18n } from "vue-i18n";
import { DwnameEnum } from "@/enums/dwnameEnum";
import { cloneDeep, pick, defaultsDeep } from "lodash-es";
import { CommonDynamicSelect } from "@/api/modules/common";
// import LjHeaderMenu from "@/components/LjHeaderMenu/index.vue";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { detailAction } from "@/components/LjDetail/interface";

import LjSelector from "@/components/LjSelector/index.vue";
import { useMtrlwareSaletask } from "./hooks/index";
import MtrlTable from "./components/mtrl.vue";
import CusTable from "./components/cus.vue";
import HistoryTable from "./components/history.vue";
import MtrlwareTable from "./components/mtrlware.vue";
import PriceTable from "./components/price.vue";
import { throttle } from "lodash-es";
import { useToast } from "vue-toastification";
import ToastErrCopy from "@/components/ToastWidget/ToastErrCopy/index.vue";
import ToastErrCopyList from "@/components/ToastWidget/ToastErrCopy/list.vue";
import { ElMessage } from "element-plus";
import { sysOptionEnum } from "@/enums/sysOptionEnum";
// import variables from "@/styles/js.module.scss";

// const props = withDefaults(defineProps<{}>(), {});

const { t } = useI18n();
const toast = useToast();
const { mtrlprpOptions, mtrloriginOptions } = useMtrlwareSaletask(t);

// const selColumnsSim: any = computed(() => {
//   let selCol: any = { type: "checkbox", width: 50, fixed: "left" };
//   let _columns = cloneDeep(columnsSim);
//   _columns.unshift(selCol);
//   console.log("_columns :>> ", _columns);
//   return _columns;
// });

const activeTable = ref("mtrldef");
const activeTableLast = ref("mtrldef");
const mtrldefRef = ref();
const cusRef = ref();
const historyRef = ref();
const mtrlwareRef = ref();
const priceRef = ref();

// const ToastMsgFunc = (tableref: any,errRow: any[], message: string) => {
//   // ElNotification({
//   //   title: t("sys.api.errorTip"),
//   //   message: "第" + errIdx.join(",") + "行<协同>状态非【采购提前待回复】或【采购延后待回复】, 不能操作！",
//   //   type: "error"
//   // });
//   toast.warning(
//     {
//       component: ToastErrCopyList,
//       props: {
//         type: "warning",
//         title: message,
//         messageList: errRow,
//         showField: {
//           field: "tid",
//           title: t("table.fx_saletask.tid")
//         }
//       },
//       listeners: {
//         messageClick: (row: any, field: string) => {
//           const $table = tableref?.element;
//           $table.setCurrentRow(row);
//           $table.scrollToRow(row, field);
//         }
//       }
//     },
//     {
//       icon: false,
//       timeout: 6000,
//       closeButton: false,
//       toastClassName: "longjoe-toast"
//     }
//   );
// };

/**
 * @description tab页切换 更新表格选中状态
 * @param name tab页名称
 * @param title tab页标题
 */
const handleTabsClick = (name: any, title: string) => {
  nextTick(() => {
    console.log("handleTabsClick activeTableLast.value, name selectList:>> ", activeTableLast.value, name);
    switch (name) {
      case "mtrldef":
        if (mtrldefRef.value) {
          mtrldefRef.value.clearCheckbox();
          mtrldefRef.value.autoUpdateTableCheckbox();
        }
        break;
      case "cust":
        if (cusRef.value) {
          cusRef.value.clearCheckbox();
          cusRef.value.autoUpdateTableCheckbox();
        }
        break;
      case "history":
        if (historyRef.value) {
          historyRef.value.clearCheckbox();
          historyRef.value.autoUpdateTableCheckbox();
        }
        break;
      case "mtrlware":
        if (mtrlwareRef.value) {
          mtrlwareRef.value.clearCheckbox();
          mtrlwareRef.value.autoUpdateTableCheckbox();
        }
        break;
      case "price":
        if (priceRef.value) {
          priceRef.value.clearCheckbox();
          priceRef.value.autoUpdateTableCheckbox();
        }
        break;
    }
  });
};

const funcSetAttr = (item: any, callback?: any) => {
  let res: any = {};
  res.mtrlid = item.mtrlid;
  res.mtrlcode = item.mtrlcode;
  res.mtrlname = item.mtrlname;
  res.mtrlmode = item.mtrlmode;
  res.unit = item.unit;
  res.mtrltype = item.mtrltype;
  res.planprice = item.planprice;
  res.mtrlsectype = item.mtrlsectype;
  res.zxmtrlmode = item.zxmtrlmode;
  res.usermtrlmode = item.usermtrlmode;

  callback && (res = callback(res));
  return res;
};

/**
 * @description 提交前检查
 */
const beforeSubmit = (data: any[]) => {
  let resArr: any = [];

  switch (activeTableLast.value) {
    case "mtrldef":
      data.map(item => {
        let res: any = funcSetAttr(item, (result: any) => {
          result.status = "";
          result.woodcode = "";
          result.pcode = "";
          result.fprice = 0;
          result.zqrate = 0;
          result.taskqty = 0;
          result.mxdscrp1 = item.mxdscrp1;
          result.mxdscrp2 = item.mxdscrp2;
          result.billid = 0;
          return result;
        });
        resArr.push(res);
      });
      break;
    case "cust":
      data.map(item => {
        let res: any = funcSetAttr(item, (result: any) => {
          result.status = item.status;
          result.woodcode = item.woodcode;
          result.pcode = item.pcode;
          result.fprice = item.fprice_bj;
          result.zqrate = item.zqrate_bj;
          result.taskqty = 0;
          result.mxdscrp1 = item.mxdscrp1;
          result.mxdscrp2 = item.mxdscrp2;
          result.billid = 0;
          return result;
        });
        resArr.push(res);
      });
      break;
    case "history":
      data.map(item => {
        let res: any = funcSetAttr(item, (result: any) => {
          result.status = item.status;
          result.woodcode = item.woodcode;
          result.pcode = item.pcode;
          result.fprice = 0;
          result.zqrate = 0;
          result.taskqty = 0;
          result.mxdscrp1 = item.mxdscrp1;
          result.mxdscrp2 = item.mxdscrp2;
          result.billid = 0;
          return result;
        });
        resArr.push(res);
      });
      break;
    case "mtrlware":
      data.map(item => {
        let res: any = funcSetAttr(item, (result: any) => {
          result.status = item.status;
          result.woodcode = item.woodcode;
          result.pcode = item.pcode;
          result.fprice = 0;
          result.zqrate = 0;
          result.taskqty = 0;
          result.mxdscrp1 = "";
          result.mxdscrp2 = "";
          result.billid = 0;
          return result;
        });
        resArr.push(res);
      });
      break;
    case "price":
      data.map(item => {
        let res: any = funcSetAttr(item, (result: any) => {
          result.status = item.status;
          result.woodcode = item.woodcode;
          result.pcode = item.pcode;
          result.fprice = item.price;
          result.zqrate = item.rebate;
          result.taskqty = 0;
          result.mxdscrp1 = "";
          result.mxdscrp2 = "";
          result.price = item.price;
          result.tax = item.tax;
          result.billid = item.pricelistid;
          result.billcode = item.listname;
          return result;
        });
        resArr.push(res);
      });
      break;
    default:
      break;
  }

  return resArr;
};

/**
 * @description 已选列表
 */
const selectList = ref<any>([]);

const LjSelectorRef = ref();
const LjTableRef = ref();
// const _variables: any = variables;
const { CheckPower, CheckOption, buttonNew, buttonDefault } = useAuthButtons(t);

const keyword = ref("");
const paramsAttrs = ["mtrlorigin", "mtrltypeid", "mtrltypeid_arr", "ifpack", "mtrlprp", "keyword", "scid", "cusid", "dftcusid"];
const initParams = ref({
  mtrlorigin: 0,
  mtrltypeid: -1,
  mtrltypeid_arr: [],
  ifpack: 1,
  mtrlprp: -1,
  keyword: "",
  dftcusid: 0
});
const tableSearchCol = { xs: 4, sm: 5, md: 6, lg: 6, xl: 8 };
const TABLE_KEY = "mtrlid";
const tableProps = {
  height: "auto",
  editConfig: { trigger: "click", mode: "cell" },
  rowConfig: { isCurrent: true, isHover: true, useKey: true, keyField: TABLE_KEY },
  checkboxConfig: {
    trigger: "row",
    range: true,
    reserve: true,
    checkMethod: ({ row }: any) => {
      return row.isuse != 0;
    }
  },
  rowClassName: ({ row, rowIndex, $rowIndex }: any) => {
    if (row.isuse == 0) {
      return "vxecol-disable";
    }
    return "";
  }
};

/**
 * @description 修改时，按钮展示
 */
const action: detailAction[] = [
  // buttonDefault({
  //   label: t("common.cancelText"),
  //   icon: "iconchevron-left",
  //   clickFunc: item => {
  //     // if (route.path.indexOf("/new") > -1) {
  //     //   tabRemove(route.fullPath);
  //     //   router.replace("/saletask/sale/saletaskCrm");
  //     // } else {
  //     //   router.replace(
  //     //     `/saletask/sale/saletaskCrm/detail?scid=${LjDetailRef.value._mainData.scid}&taskid=${LjDetailRef.value._mainData.taskid}&code=${LjDetailRef.value._mainData.taskcode}`
  //     //   );
  //     // }
  //   }
  // }),
  // buttonDefault({
  //   label: t("common.saveText"),
  //   icon: "iconsave-01",
  //   path: "/saletask/sale/saletaskCrm/new"
  // })
];

const selectedLayout = ref<any>({
  icon: "iconmove",
  header: [
    {
      value: "mtrlname",
      // icon: "iconuser-01",
      textClassName: "text-ellipsis-one2"
    },
    {
      value: "mtrlcode",
      // label: "描述",
      icon: "iconcode",
      textClassName: "text-ellipsis-one2"
    }
  ]
  // aside: {
  //   value: "cuscode"
  // }
});

const getMtrltype = async () => {
  const data = await getL1MtrlType({ RecurionType: 1 });
  return data.RecurionList;
};

const changeTreeFilter = (val: any, valArr: any) => {
  console.log("val :>> ", val);
  initParams.value.mtrltypeid = val ?? -1;
  initParams.value.mtrltypeid_arr = valArr;
  console.log("val :>>Children Values:", initParams.value);
};

const autoUpdateTableCheckbox = () => {
  switch (activeTable.value) {
    case "mtrldef":
      mtrldefRef.value.autoUpdateTableCheckbox();
      break;
    case "cust":
      cusRef.value.autoUpdateTableCheckbox();
      break;
    case "history":
      historyRef.value.autoUpdateTableCheckbox();
      break;
    case "mtrlware":
      mtrlwareRef.value.autoUpdateTableCheckbox();
      break;
    case "price":
      priceRef.value.autoUpdateTableCheckbox();
      break;
  }
  // // const $table = LjTableRef.value.element;
  // if ($table && selectList.value.length) {
  //   console.log("autoUpdateTableCheckbox selectLst.value :>> ", selectList.value);
  //   $table.clearCheckboxRow();
  //   // $table.setCheckboxRow(selectList.value, true);
  //   let _rows: any = [];
  //   selectList.value.map((item: any) => {
  //     if ($table.getRowById(item[TABLE_KEY])) {
  //       // $table.setCheckboxRow($table.getRowById(item.cusid), true);
  //       _rows.push($table.getRowById(item[TABLE_KEY]));
  //     }
  //   });
  //   _rows.length && $table.setCheckboxRow(_rows, true);
  // }
};

/**
 * @description 选择后，回调检查
 * @param list 选中数据列
 * @param target tableRef
 */
const autoSelectedChange = (list: any, target?: any) => {
  console.log("autoSelectedChange list :>> ", list);
  selectList.value = list;
  activeTableLast.value = activeTable.value;
  LjSelectorRef.value.changeActiveCollapse("selected");

  // 检查选择合法性
  if (target) {
    const curRecords = target.getCheckboxRecords() ?? [];
    console.log("curRecords :>> ", curRecords);

    let errRow: any = [];
    curRecords.map((item: any, index: number) => {
      if (Number(item.isuse) == 0) {
        errRow.push(item);
      }
    });

    if (errRow.length) {
      toast.warning(
        {
          component: ToastErrCopyList,
          props: {
            type: "warning",
            title: t("business.error.selector.mtrlisuse1") + errRow.length + t("business.error.selector.mtrlisuse2"),
            messageList: errRow,
            showField: {
              field: "mtrlcode",
              title: t("table.u_mtrldef.mtrlcode")
            }
          },
          listeners: {
            messageClick: (row: any, field: string) => {
              target.setCurrentRow(row);
              target.scrollToRow(row, field);
            }
          }
        },
        {
          icon: false,
          timeout: 6000,
          closeButton: false,
          toastClassName: "longjoe-toast"
        }
      );
    }
  }
};

// 节流
const disshow = throttle((val: any) => {
  console.log("val :>> ", val);
  initParams.value.keyword = val;
}, 500);

/**
 * @description 点击表格行
 */
const handleCellClick = (params: any) => {
  const { row } = params;
  if (row.isuse == 0) {
    ElMessage.warning(t("business.error.selector.mtrlisuse"));
  }
  return true;
};

/**
 * @description 打开组件
 * @param params 入参
 */
const show = (params: any) => {
  selectList.value = [];
  console.log("show params :>> ", params);
  initParams.value = defaultsDeep(params, initParams.value);

  let option558 = Number(CheckOption(sysOptionEnum.sys_option_558));
  if (params.ori_dftcusid_sale_check == option558 || option558 == 3) {
    initParams.value.dftcusid = params.cusid;
  } else {
    initParams.value.dftcusid = 0;
  }
  console.log("initParams.value :>> ", initParams.value);
  LjSelectorRef.value.show(initParams.value, "mtrl");
};

defineExpose({
  show
});
</script>

<style lang="scss" scoped>
.lj-van-tabs-flex-full {
  :deep(.van-tabs__nav) {
    .van-tabs__line {
      background: $color-primary-500;
    }
  }
}
</style>
