<template>
  <LjDialog
    ref="LjDrawerFjFileRef"
    v-bind="{
      ...drawerDefineProp,
      ...drawerProp,
      ...{
        closeOnPressEscape: initialIndex != -1
      }
    }"
    :style="{ height: '50%' }"
    :closed="autoClosed"
  >
    <template #header>
      <div class="flx-1">
        <span class="text-h5-b">附件档案</span>
      </div>
    </template>
    <LjFoldLayoutDouble ref="LjFoldLayoutDoubleRef" v-bind="layoutDefault">
      <template #firstLeft>
        <aside class="rapmoney-aside">
          <el-collapse v-model="activeNames" class="saleprice-aside-collapse h-full card pt-2 pb-8">
            <el-collapse-item title="附件分类" name="saleprice">
              <template v-if="fileClassList.length">
                <template v-for="(item, index) in fileClassList" :key="index">
                  <SalePriceItem
                    v-bind="fileClassListLayout"
                    keyattr="classid"
                    :current="initParams.classid"
                    :data="item"
                    @click-item="handleSelectItem"
                  />
                </template>
              </template>
              <template v-else>
                <van-empty image="search" :description="$t('sys.empty.nodate')"> </van-empty>
              </template>
            </el-collapse-item>
          </el-collapse>
        </aside>
      </template>
      <template #secondMain>
        <div class="flx h-full">
          <LjVxeTable
            ref="LjFileRef"
            row-key="key"
            :request-api="getData"
            :data-callback="dataCallback"
            :init-param="initParams"
            :columns="columns"
            :dwname="DwnameEnum.fjFile"
            :table-props="tableProps"
            :table-events="tableEvents"
            :tool-button="['refresh', 'setting']"
            :request-auto="false"
          >
            <template #tableHeader>
              <UploadWidget :params="initParams" :limit="props.limit" @uploaded="autoUploaded">
                <template #default="scope">
                  <el-button
                    v-if="addPower && CheckPower(addPower)"
                    type="primary"
                    :plain="selectList.length > 0"
                    @click="scope.show"
                  >
                    <template #icon>
                      <i class="iconfont iconupload-01"></i>
                    </template>
                    {{ $t("common.uploadFile") }}
                  </el-button>
                </template>
              </UploadWidget>
              <el-button
                v-if="powerList.includes('save')"
                :disabled="!selectList.length"
                type="primary"
                :plain="!selectList.length"
                @click="downloadRowEvent(selectList)"
              >
                <template #icon>
                  <i class="iconfont icondownload-01"></i>
                </template>
                <span class="text-body-c">{{ `${$t("common.download")}${selectSize ? "(" + selectSize + ")" : ""}` }}</span>
              </el-button>
              <el-button
                v-if="powerList.includes('del')"
                :disabled="!selectList.length"
                type="danger"
                plain
                @click="delRowEvent(selectList)"
              >
                <template #icon>
                  <i class="iconfont icontrash-02"></i>
                </template>
                <span class="text-body-c">{{ `${$t("common.delText")}(${selectList.length})` }}</span>
              </el-button>
            </template>
            <template #operation="scope" v-if="powerList.includes('edit') || powerList.includes('del')">
              <template v-if="isActiveStatus(scope.row)">
                <el-button type="success" plain circle size="small" @click="saveRowEvent(scope.row)">
                  <template #icon>
                    <i class="iconfont iconsave-01" style="font-size: 12px"></i>
                  </template>
                </el-button>
                <el-button type="info" plain circle size="small" @click="cancelRowEvent(scope.row)">
                  <template #icon>
                    <i class="iconfont iconwrong_light" style="font-size: 12px"></i>
                  </template>
                </el-button>
              </template>
              <template v-else>
                <el-button type="primary" plain circle size="small" @click="editRowEvent(scope.row)">
                  <template #icon>
                    <i class="iconfont iconedit-02" style="font-size: 12px"></i>
                  </template>
                </el-button>
                <el-popconfirm :title="$t('business.tips.file.delConfirm')" @confirm="delRowEvent(scope.row)">
                  <template #reference>
                    <el-button type="danger" plain circle size="small">
                      <template #icon>
                        <i class="iconfont icontrash-02" style="font-size: 12px"></i>
                      </template>
                    </el-button>
                  </template>
                </el-popconfirm>
              </template>
            </template>
          </LjVxeTable>
        </div>
      </template>
    </LjFoldLayoutDouble>

    <LjFilePreview ref="LjFilePreviewRef" v-model:files="fileList" :initial-index="initialIndex" @closed="autoClosedPreview" />
  </LjDialog>
</template>

<script setup lang="tsx" name="LjFile">
import { ref, onMounted, nextTick, computed, inject } from "vue";
import { Search, Files } from "@element-plus/icons-vue";
import LjDialog from "@/components/LjDialog/index.vue";
import LjFoldLayoutDouble from "@/components/LjFoldLayoutDouble/index.vue";
import { DwnameEnum } from "@/enums/dwnameEnum";
import { CommonDynamicSelect, CommonBill, DownloadCacheFile } from "@/api/modules/common";
import { getL1MtrlType } from "@/api/modules/technology";
import { traverseNode, getBase64Type, formatAmount3 } from "@/utils/index";
import SalePriceItem from "@/views/saletask/salePrice/components/SalePriceItem.vue";
import LjVxeTable from "@/components/LjVxeTable/index.vue";
import { useFjFile } from "./hooks/index";
import { useI18n } from "vue-i18n";
import { cloneDeep, pick, get, omit, defaultsDeep } from "lodash-es";
import { getDifference, setDifference, handleProp, streamlineFunc, streamlineAttrFunc, convertStrToObj } from "@/utils";
import { formatToDateTime } from "@/utils/dateUtil";
import { GetFjFile, GetCacheFile } from "@/api/modules/common";
import variables from "@/styles/js.module.scss";
import LjFilePreview from "@/components/LjFilePreview/index.vue";
import UploadWidget from "./components/UploadWidget.vue";
import { ElMessage } from "element-plus";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { isArray } from "@/utils/is";
import { blobType } from "@/config/blobType";
import axios from "axios";

interface LjFileProps {
  /**
   * @description 抽屉基础属性
   */
  drawerProp?: any;
  /**
   * @argument 附件上传权限
   */
  addPower?: number;
  /**
   * @description 允许上传文件的最大数量
   */
  limit?: number;
}

export interface FileParams {
  /**
   * @description 附件类型id
   */
  billtype?: number;
  classid?: number;
  relid?: number;
  relidmx?: number;
  scid?: number | undefined;
  relcode?: string | undefined;
}

const props = withDefaults(defineProps<LjFileProps>(), {
  addPower: 0,
  limit: 50,
  drawerProp: {
    width: "80%",
    "destroy-on-close": true
  }
});

const { t } = useI18n();
const { CheckPower } = useAuthButtons(t);
const LjFoldLayoutDoubleRef = ref();
const LjDrawerFjFileRef = ref();
const LjFilePreviewRef = ref();
const LjFileRef = ref();
const activeNames = ref(["saleprice"]);
const isEditing = ref(false);
const initialIndex = ref(0);
const powerList = ref<any>([]);
const _variables: any = variables;

const layoutDefault: any = {
  first: {
    left: {
      minWidth: "0"
      // minWidth: "20%"
    }
  },
  params: {}
};

const initParams = ref<FileParams>({
  billtype: 0
  // classid: 0
});

const selectList = ref([]);

const selectSize = computed(() => {
  if (!selectList.value.length) return "";
  let _size = 0;
  selectList.value.map((item: any) => {
    _size += item.filekb;
  });
  if (_size < 1024) {
    return formatAmount3({ val: _size }) + "b";
  } else if (_size < 1024 * 1024) {
    return formatAmount3({ val: _size / 1024 }) + "Kb";
  } else if (_size < 1024 * 1024 * 1024) {
    return formatAmount3({ val: _size / 1024 / 1024 }) + "Mb";
  } else {
    return formatAmount3({ val: _size / 1024 / 1024 / 1024 }) + "Gb";
  }
});

const handleCheckboxChange = (data: any) => {
  selectList.value = data.records;
};

// const getSelectList = () => {
//   const $table = LjFileRef.value?.element;
//   let list = [];
//   if ($table) {
//     list = $table.getCheckboxRecords();
//   }
//   return list;
// };

// watch(
//   () => LjFoldLayoutDoubleRef.value.currentLayout,
//   newVal => {
//     console.log("LjFoldLayoutDoubleRef.value.currentLayout !!! newVal :>> ", newVal);
//     // if (newVal.dwname === "u2_mx_money") {
//     //   initParams.value = defaultsDeep(newVal.params, layoutDefault.params);
//     //   mainData.value = 1;
//     //   nextTick(() => {
//     //     LjFoldLayoutDoubleRef.value.handleFoldChange(true);
//     //   });
//     // }
//   }
// );
/**
 * @description 销售明细-单元格样式
 */
const cellStyle = ({ row, column }: any) => {
  if (column.field === "fileName") {
    return {
      color: _variables.colorGeekBlue6,
      cursor: "pointer",
      textDecoration: "underline"
    };
  }
};

const headerCellStyle = ({ column }: any) => {
  if (isEditing.value && powerList.value.includes("edit")) {
    if (column.field === "fileName" || column.field === "dscrp") {
      return {
        color: _variables.colorGeekBlue5
      };
    }
  }
};

/**
 * @description 附件分类列表
 */
const fileClassList = ref([] as any[]);
/**
 * @description 附件列表
 */
const fileList = ref<any>([]);
const previewList = ref([]);

const isSrcList = computed(() => {
  let arr: any = [];
  fileList.value.map((item: any) => {
    if (item.fileData) {
      // const blob = new Blob([item.filedata + "." + item.fileType]);
      // // 兼容 edge 不支持 createObjectURL 方法
      // // if ("msSaveOrOpenBlob" in navigator) return window.navigator.msSaveOrOpenBlob(blob, item.fileName + item.fileType);
      // const blobUrl = window.URL.createObjectURL(blob);

      // console.log("blobUrl :>> ", blobUrl);

      arr.push(item.fileData);
    } else {
      arr.push("filemd5:" + item.filemd5);
    }
  });
  return arr;
});

const { columns } = useFjFile(t);

// const rowClsNameFunc = (data: any) => {
//   const { row, rowIndex, $rowIndex } = data;
//   if (row.flag == "0") {
//     return "vxecol-danger";
//   }
//   return "";
// };
const tableProps = {
  height: "auto",
  minHeight: "300px",
  maxHeight: "600px",
  cellStyle: cellStyle,
  headerCellStyle: headerCellStyle,
  editConfig: { trigger: "manual", mode: "row" },
  keepSource: true
};

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

// 修改表头样式
// const headerCellClassName = ({ column }: any) => {
//   if (column?.editRender) {
//     return "vxecol-edit";
//   }
//   return null;
// };

const fileClassListLayout = ref<any>({
  // icon: "iconPaper_light",
  header: [
    {
      value: "classname",
      icon: Files
    },
    {
      icon: (data: any) => {
        let _type = "iconeye-off";
        let _color = _variables.colorTextDisable;
        if (data.allow_view === "1") {
          _type = "iconeye";
          _color = _variables.colorTextPrimaryText;
        }

        return <i class={["iconfont", _type]} style={{ color: _color }} />;
      }
    },
    {
      icon: (data: any) => {
        let _type = "iconedit-02-off";
        let _color = _variables.colorTextDisable;
        if (data.allow_edit === "1") {
          _type = "iconedit-02";
          _color = _variables.colorTextPrimaryText;
        }

        return <i class={["iconfont", _type]} style={{ color: _color }} />;
      }
    },
    {
      icon: (data: any) => {
        let _type = "icontrash-02-off";
        let _color = _variables.colorTextDisable;
        if (data.allow_del === "1") {
          _type = "icontrash-02";
          _color = _variables.colorTextPrimaryText;
        }

        return <i class={["iconfont", _type]} style={{ color: _color }} />;
      }
    },
    {
      icon: (data: any) => {
        let _type = "icondownload-off";
        let _color = _variables.colorTextDisable;
        if (data.allow_save === "1") {
          _type = "icondownload-01";
          _color = _variables.colorTextPrimaryText;
        }

        return <i class={["iconfont", _type]} style={{ color: _color }} />;
      }
    },
    {
      value: "dscrp",
      label: "描述"
      // tag: [
      //   {
      //     value: "allow_view",
      //     position: "left",
      //     icon: (data: any) => {
      //       let _type = "iconcopy-03";
      //       if (data.allow_view === "1") {
      //         _type = "icontrash-01";
      //       }

      //       return <i class={["iconfont", _type]} />;
      //     },
      //     prop: {
      //       type: (data: any) => {
      //         let _type = "info";
      //         if (data.allow_view === "1") {
      //           _type = "success";
      //         }
      //         return _type;
      //       },
      //       size: "small"
      //     }
      //   },
      //   {
      //     value: "allow_edit",
      //     position: "left",
      //     icon: (data: any) => {
      //       let _type = "iconcopy-03";
      //       if (data.allow_edit === "1") {
      //         _type = "icontrash-01";
      //       }

      //       return <i class={["iconfont", _type]} />;
      //     },
      //     prop: {
      //       type: (data: any) => {
      //         let _type = "info";
      //         if (data.allow_edit === "1") {
      //           _type = "success";
      //         }
      //         return _type;
      //       },
      //       size: "small"
      //     }
      //   },
      //   {
      //     value: "allow_del",
      //     position: "left",
      //     prop: {
      //       type: (data: any) => {
      //         let _type = "info";
      //         if (data.allow_del === "1") {
      //           _type = "success";
      //         }
      //         return _type;
      //       },
      //       size: "small"
      //     },
      //     enum: [
      //       {
      //         value: 0,
      //         label: "无权删除"
      //       },
      //       {
      //         value: 1,
      //         label: "允许删除"
      //       }
      //     ]
      //   }
      // ]
    }
  ]
});

/**
 * @description 计算附件分类权限
 * @param type 动作
 */
const checkAllowPower = (data: any) => {
  let allow = [];
  console.log("Boolean(data.allow_edit) :>> ", data, Boolean(data.allow_edit));
  Boolean(Number(data.allow_edit)) && allow.push("edit");
  Boolean(Number(data.allow_del)) && allow.push("del");
  Boolean(Number(data.allow_save)) && allow.push("save");
  Boolean(Number(data.allow_view)) && allow.push("view");
  powerList.value = allow;
};

const getList = async (params: any, callback?: any) => {
  console.log("getData params :>> ", params);
  let newParams: any = {};
  newParams.queryParams = params;
  newParams.dsname = "web_fj_fileclass_list";
  let data = await CommonDynamicSelect(newParams, "");
  console.log("getList data :>> ", data);
  fileClassList.value = data.datatable;

  callback && callback(data);
};

/**
 * @description 点击列表
 */
const handleSelectItem = (data: any) => {
  if (!Boolean(Number(data.allow_view))) {
    ElMessage.error("你没有权限查看");
    return false;
  }
  console.log("handleSelectItem data :>> ", data);
  initParams.value.classid = Number(data.classid);
  checkAllowPower(data);
};

const getData = (params: any) => {
  console.log("fjfile_getData params :>> ", params);
  let newParams: any = {};
  newParams.fjdata = { ...params, ...props };
  return GetFjFile(newParams);
};

const dataCallback = (data: any) => {
  console.log("dataCallback data :>> ", data);
  fileList.value = data.FjFileList;
  return {
    list: data.FjFileList
  };
};

/**
 * @description 展示组件
 * @param data
 */
const show = async (data: any) => {
  LjDrawerFjFileRef.value.show();
  initParams.value = data;

  console.log("show getList data :>> ", data);
  console.log("show initParams.value :>> ", initParams.value);

  await getList({ billtype: data.billtype }, (res: any) => {
    console.log("show getList res :>> ", res);
    if (res.datatable.length) {
      let _idx = res.datatable.findIndex((itm: any) => Boolean(Number(itm.allow_view)));
      _idx > -1 && handleSelectItem(res.datatable[_idx]);
    }
  });
};

/**
 * @description 预览图片：关闭组件后的操作
 */
const autoClosed = () => {
  // initParams.value = {
  //   billtype: 0
  // };
  initParams.value.classid = 0;
  console.log("autoClosed initParams.value :>> ", initParams.value);
};

const getFileData = async (md5Str: string, index?: number) => {
  let params = { filemd5: md5Str };
  return await GetCacheFile(params);
  // const blob = new Blob(["data:image/jpg;base64," + res.filedata]);
  // const blob = new Blob([res], { type: "image/jpg" });
  // const blob = new Blob([res], { type: "image/jpg" });
  // 兼容 edge 不支持 createObjectURL 方法
  // if ("msSaveOrOpenBlob" in navigator) return window.navigator.msSaveOrOpenBlob(blob, item.fileName + item.fileType);
  // const blobUrl = window.URL.createObjectURL(blob);
  // fileList.value[index].fileData = "data:image/png;base64," + res.filedata;
};

// /**
//  * @description 预览图片：切换组件的操作
//  */
// const handleSwitchImageViewer = async (index: any) => {
//   console.log("handleSwitchImageViewer index :>> ", index);

//   if (fileList.value.length < index + 1) {
//     return;
//   }

//   let str = isSrcList.value[index];
//   console.log("handleSwitchImageViewer str :>> ", str);
//   if (str.indexOf("filemd5:") > -1) {
//     let _str = str.replace("filemd5:", "");
//     await getFileData(_str, index);
//   }
// };

function b64toBlob(b64Data: any, contentType: any, sliceSize = 512) {
  let b = b64Data.toString();

  b64Data = b.split(",")[1];
  console.log("b64Data :>> ", b64Data);

  let byteCharacters = atob(b64Data);

  let byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    let slice = byteCharacters.slice(offset, offset + sliceSize);

    let byteNumbers = new Array(slice.length);

    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    let byteArray = new Uint8Array(byteNumbers);

    byteArrays.push(byteArray);
  }
  console.log("byteArrays :>> ", byteArrays);

  let blob = new Blob(byteArrays, { type: contentType });

  return blob;
}

/**
 * @description 销售明细-鼠标单击表格
 */
const handleClickTable = async ({ row, column, rowIndex }: any) => {
  if (column.field === "fileName" && !isEditing.value) {
    initialIndex.value = rowIndex;
    console.log("handleClickTable rowIndex :>> ", rowIndex);
    LjFilePreviewRef.value.show();
  }
};

const autoClosedPreview = () => {
  initialIndex.value = -1;
  console.log("autoClosedPreview  :>> ", initialIndex.value);
};

/**
 * @description 判断是否正在编辑
 * @param row
 */
const isActiveStatus = (row: any) => {
  const $table = LjFileRef.value.element;
  if ($table) {
    return $table.isEditByRow(row);
  }
};

/**
 * @description 关闭后，还原数据
 * @param row
 */
const autoEditClosed = ({ row }: any) => {
  const $table = LjFileRef.value.element;
  if ($table) {
    isEditing.value = false;
    $table.revertData(row);
  }
};

/**
 * @description 按钮：取消编辑，还原数据
 * @param row
 */
const cancelRowEvent = (row: any) => {
  const $table = LjFileRef.value.element;
  if ($table) {
    $table.clearEdit().then(() => {
      // 还原行数据
      $table.revertData(row);
    });
  }
};

/**
 * @description 按钮：编辑
 * @param row
 */
const editRowEvent = (row: any) => {
  const $table = LjFileRef.value.element;
  console.log("editRowEvent $table :>> ", $table);
  if ($table) {
    isEditing.value = true;
    $table.setEditRow(row);
  }
};

/**
 * @description 按钮：保存，后刷新
 * @param row
 */
const saveRowEvent = (row: any) => {
  const $table = LjFileRef.value.element;
  if ($table) {
    let { updateRecords } = $table.getRecordset();

    if (updateRecords.length) {
      let _row = updateRecords[0];
      CommonBill({
        uoName: "uo_fj_mng_billtype",
        functionName: "uf_edit_fj",
        SParms: {
          arg_s_fileinfo: {
            fileid: _row.fileid,
            fileName: _row.fileName.trim(),
            dscrp: _row.dscrp.trim()
          },
          arg_msg: ""
        },
        ifcommit: true,
        returnStrList: []
      }).then((res: any) => {
        isEditing.value = false;
        ElMessage.success(t("sys.api.operationSuccess"));
        LjFileRef.value.refresh();
      });
    }
  }
};

/**
 * @description 按钮：删除，后刷新
 * @param row
 */
const delRowEvent = (row: any) => {
  let fileids = [];
  if (isArray(row)) {
    row.forEach((item: any) => {
      fileids.push(item.fileid);
    });
  } else {
    fileids.push(row.fileid);
  }
  CommonBill({
    uoName: "uo_fj_mng_billtype",
    functionName: "uf_del_file",
    SParms: {
      arg_fileids: fileids,
      arg_msg: ""
    },
    ifcommit: true,
    returnStrList: []
  }).then((res: any) => {
    ElMessage.success(t("sys.api.operationSuccess"));
    LjFileRef.value.refresh();
  });
};

const funcDownload = (data: any, blob: any) => {
  // // 创建一个Blob对象，类型为txt
  // const blob = new Blob([txtContent], { type: "text/plain;charset=utf-8" });
  // let _blobtype = Object.keys(blobType).includes(data.fileType) ? blobType[data.fileType] : "text/plain;charset=utf-8";
  // const blob = b64toBlob(getBase64Type(data.fileType) + data.filedata, _blobtype, 1024);

  // 创建一个指向Blob的URL
  const url = URL.createObjectURL(blob);
  console.log("url :>> ", url);

  // 创建一个a标签并设置属性
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", String(data.fileName).trim() + "." + data.fileType);

  // 触发下载
  document.body.appendChild(link);
  link.click();

  // 清理
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};

/**
 * @description 按钮：下载
 */
const downloadRowEvent = async (data: any) => {
  console.log("downloadRowEvent data :>> ", data);

  const requests = data.map((item: any) => DownloadCacheFile({ filemd5: item.filemd5 }));
  const responses = await axios.all(requests);

  responses.forEach((blob: any, index) => {
    let downloadElement = document.createElement("a");
    let href = window.URL.createObjectURL(blob); //创建下载的链接
    downloadElement.href = href;
    downloadElement.download = data[index].fileName; //下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(href); //释放掉blob对象
  });
};

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

const autoUploaded = () => {
  LjFileRef.value.refresh();
};

defineExpose({
  show
});
</script>

<style lang="scss">
.rapmoney-aside {
  height: 100%;
  display: flex;
  flex-direction: column;

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

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

.lj-file-dialog {
  .lj-dialog {
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  .el-dialog__header {
    flex-shrink: 0;
  }
  .el-dialog__body {
    flex: 1;
    overflow: hidden;
    padding: 0;
  }

  .longjoe-fold-layout {
    .card {
      border: unset;
    }
    .rapmoney-aside {
      .card {
        border-radius: 0;
        border-right: 1px solid var(--el-border-color-light);
      }
    }
  }
  .longjoe-fold-layout-main {
    .table-main {
      padding-top: 8px;
      padding-bottom: 8px;
    }
  }

  .el-collapse-item {
    display: flex;
    flex-direction: column;
    height: 100%;

    .el-collapse-item__wrap {
      flex: 1;
      overflow: auto;
    }
  }
}
</style>
