<template>
  <div class="main-box">
    <LjFoldLayout ref="LjFoldLayoutRef" v-bind="layoutSetting" :dwname="dwname">
      <template #left>
        <TreeFilter
          ref="LjTreeRef"
          id="mtrltypeid"
          title="物料分类"
          label="mtrltype"
          :expand-on-click-node="true"
          :request-api="gMtrltypeList"
          @change="changeTreeFilter"
        />
      </template>
      <div class="main-box flx-col">
        <LjVxeTable
          ref="VxeTableRef"
          row-key="mtrlid"
          :columns="columns"
          :request-api="getData"
          :data-callback="dataCallback"
          :dwname="dwname"
          :table-props="tableProps"
          :table-events="tableEvents"
          :tool-button="['export', 'refresh', 'setting', 'search', 'location']"
          :init-param="initParams"
          :auto-load-layout="false"
          pagination
        >
          <!-- 表格 header 按钮 -->
          <template #tableHeader>
            <el-button-group>
              <el-button @click="handleOpenNewTable">{{ $t("common.add") }}</el-button>
              <el-button @click="fDelete">{{ $t("common.delText") }}</el-button>
              <el-button @click="fBan">{{ $t("common.disable") }}</el-button>
              <el-button @click="handleShowPriceListForm">价格表复制</el-button>
              <el-button @click="handleCopyMtrldef">物料复制</el-button>
              <el-button @click="handleShowCopyForm">批修改</el-button>
              <el-button @click="handleModifyPrice">批修改单价</el-button>
              <el-button @click="handleImportData">读取单价</el-button>
            </el-button-group>
          </template>
        </LjVxeTable>
      </div>
    </LjFoldLayout>
  </div>

  <LjDialog
    ref="LjDrawerRef"
    class="is-selector"
    v-bind="{
      ...drawerDefineProp
    }"
    :style="{ padding: 0 }"
  >
    <template #header>
      <div class="flx-1">
        <span class="text-h5-b">物料: {{ mtrlname }}</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>

  <el-dialog v-model="copyFormVisible" title="物料批修改" width="500" draggable append-to-body>
    <el-form label-width="80px">
      <el-form-item label="修改字段">
        <el-select v-model="copyFormCol" value-key="title" @change="copyFormValue = ''">
          <el-option v-for="(col, index) in copyFormOption" :key="index" :label="col.title" :value="col"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="修改内容">
        <el-input v-model="copyFormValue" :type="copyFormCol.datatype ?? 'text'"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="copyFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCopyFormConfirm">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="priceListFormVisiable" title="价格表选择" width="500" draggable append-to-body>
    <el-form label-width="80px">
      <el-form-item label="源头" v-if="priceListVisiable">
        <el-select v-model="priceListFormParams.pricelistid_from">
          <el-option
            v-for="(col, index) in priceListEnum"
            :key="index"
            :label="col.pricelistname"
            :value="col.pricelistid"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="比例" required>
        <el-input v-model="priceListFormParams.rate" type="number" min="0"></el-input>
      </el-form-item>
      <el-form-item label="目标" v-if="priceListVisiable">
        <el-select v-model="priceListFormParams.pricelistid_to">
          <el-option
            v-for="(col, index) in priceListEnum"
            :key="index"
            :label="col.pricelistname"
            :value="col.pricelistid"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="copyFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePriceListCopyConfirm">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <ImportPrice ref="ImportPriceRef" @closed="toGetPriceList" />
</template>

<script setup lang="ts" name="baseinfo_mtrldeflist">
import { ref, onMounted, provide } from "vue";
import { getMtrlDefList, ModifyMtrlDefList, CopyMtrlDef } from "@/api/modules/basicinfo";
import { getPriceList } from "@/api/modules/saleprice";
import { useHooks as useHooks_mtrltype } from "@/views/baseinfo/mtrltype/hooks/index";
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 { cloneDeep } from "lodash-es";
import { traverseNode } from "@/utils/index";
import { ElMessage, ElMessageBox } from "element-plus";
import { getCurrentRecords } from "@/utils/index";
import ImportPrice from "./components/ImportPrice.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";

const dwname = "web_mtrldeflist";
const mainData = ref({});
const mtrltype = ref({});
// const initParams = ref({ mtrltypeids: undefined as Number[] });
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 ImportPriceRef = ref();

const layoutSetting = {
  dwname: dwname,
  right: {
    hidden: true
  }
};

const { t } = useI18n();
const {
  VxeTableRef,
  LjDetailRef,
  VxeTableMxRef,
  columns,
  fDelete,
  fSave,
  fBan,
  copyFormVisible,
  copyFormCol,
  copyFormValue,
  copyFormOption,
  priceListEnum,
  priceListFormVisiable,
  priceListFormParams,
  priceListVisiable,
  initParams
} = useHooks(t);
const { gMtrltypeList } = useHooks_mtrltype(t);
const { CheckPower, CheckOption, buttonNew, buttonDefault } = useAuthButtons(t);

const orderStatus = ref("");
const mtrlname = 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 => {
      const save_data = orderStatus.value == "new" ? LjDetailRef.value?.infoParam : LjDetailRef.value?._mainData;

      save_data.mxlist = VxeTableMxRef.value?.tableData;
      fSave({ mtrl: save_data }).then(() => {
        LjDrawerRef.value.hide();
      });
    }
  })
];
const orderEditAction = [
  buttonNew({
    label: t("common.saveText"),
    icon: "iconsave-01",
    clickFunc: item => {
      const save_data = LjDetailRef.value?._mainData;

      if (orderStatus.value == "new" || orderStatus.value == "copy") save_data.mtrlid = 0;
      let { fullData } = VxeTableMxRef.value?.element.getTableData();
      save_data.mxlist = fullData;
      fSave({ mtrl: save_data }).then(() => {
        LjDrawerRef.value.hide();
      });
    }
  })
];

const changeTreeFilter = (val: any) => {
  console.log("val :>> ", val);
  let mtrltypeids = [] as Number[];
  traverseNode(val, (node: any) => node?.mtrltypeid >= 0 && mtrltypeids.push(parseInt(node.mtrltypeid)));
  initParams.value.mtrltypeids = mtrltypeids.length > 0 ? mtrltypeids : undefined;
};

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

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

const dataCallback = (data: any) => {
  if (data.tableinfo?.columns) {
    data.tableinfo?.columns.map((item: any) => {
      if (item?.enum) {
        enumMap.value.set(item.field, item.enum);
      }
    });
  }
  return {
    list: data.list,
    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);
  mtrlname.value = row.name;
  orderStatus.value = "edit";
  LjDrawerRef.value.show();
};

const handleOpenNewTable = () => {
  mainData.value = {
    mtrlid: 0
  };
  mtrlname.value = "";
  orderStatus.value = "new";
  LjDrawerRef.value.show();
};

const handleCopyMtrldef = () => {
  const { curRecords } = getCurrentRecords(VxeTableRef.value);

  console.log("curRecords :>> ", curRecords);
  if (!curRecords.length) {
    ElMessage.warning(t("business.tips.mattress.records"));
    return;
  }

  if (curRecords.length > 1) {
    ElMessage.warning("无法选择多个物料复制");
    return;
  }

  // 弹窗
  const copy_row = curRecords[0];
  mainData.value = cloneDeep(copy_row);
  mtrlname.value = copy_row.name;
  orderStatus.value = "copy";
  LjDrawerRef.value.show();
};

const handleShowCopyForm = () => {
  const { curRecords } = getCurrentRecords(VxeTableRef.value);

  console.log("curRecords :>> ", curRecords);
  if (!curRecords.length) {
    ElMessage.warning(t("business.tips.mattress.records"));
    return;
  }

  copyFormVisible.value = true;
};

const handleCopyFormConfirm = () => {
  console.log(copyFormCol);

  const { curRecords } = getCurrentRecords(VxeTableRef.value);

  console.log("curRecords :>> ", curRecords);
  if (!curRecords.length) {
    ElMessage.warning(t("business.tips.mattress.records"));
    return;
  }

  curRecords.forEach(element => {
    element[copyFormCol.value.field] = copyFormValue.value;
  });

  ModifyMtrlDefList({ list: curRecords })
    .then(() => {
      copyFormVisible.value = false;

      ElMessage.success("修改成功！");
      VxeTableRef?.value.refresh();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "操作取消"
      });
    });
};

const handleShowPriceListForm = () => {
  const { curRecords } = getCurrentRecords(VxeTableRef.value);

  console.log("curRecords :>> ", curRecords);
  if (!curRecords.length) {
    ElMessage.warning(t("business.tips.mattress.records"));
    return;
  }

  priceListFormVisiable.value = true;
  priceListVisiable.value = true;
};

const handlePriceListCopyConfirm = () => {
  const { curRecords } = getCurrentRecords(VxeTableRef.value);

  console.log("curRecords :>> ", curRecords);
  if (!curRecords.length) {
    ElMessage.warning(t("business.tips.mattress.records"));
    return;
  }

  curRecords.forEach(element => {
    element[copyFormCol.value.field] = copyFormValue.value;
  });

  let mtrlids = [];

  if (!priceListVisiable.value) {
    mtrlids = curRecords.map(item => item.mtrlid);
  }

  ElMessageBox.confirm(`是否确定要更新价格表单价?`, "询问", {
    confirmButtonText: "是",
    cancelButtonText: "否",
    type: "warning"
  })
    .then(() => {
      CopyMtrlDef({
        pricelistid_from: priceListFormParams.value.pricelistid_from,
        pricelistid_to: priceListFormParams.value.pricelistid_to,
        rate: priceListFormParams.value.rate,
        mtrlids
      }).then(() => {
        priceListFormVisiable.value = false;

        ElMessage.success(`更新价格表单价成功！`);
        VxeTableRef?.value.refresh();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "操作取消"
      });
    });
};

const handleModifyPrice = () => {
  const { curRecords } = getCurrentRecords(VxeTableRef.value);

  console.log("curRecords :>> ", curRecords);
  if (!curRecords.length) {
    ElMessage.warning(t("business.tips.mattress.records"));
    return;
  }

  priceListVisiable.value = false;
  priceListFormVisiable.value = true;

  priceListFormParams.value.pricelistid_from = curRecords[0].pricelistid;
  priceListFormParams.value.pricelistid_to = curRecords[0].pricelistid;
  priceListFormParams.value.rate = 1;
};
const handleImportData = () => {
  ImportPriceRef.value.show();
};
// 返回绑定的事件
const tableEvents = {
  "cell-dblclick": handleDBlClickTable
  // "cell-click": handleClickTable
};

const toGetPriceList = () => {
  VxeTableRef.value.refresh();
};
</script>
