import axios from "axios";
import {
  formatter,
  formatterAmount,
  formatterDate,
  formatterDateOnly,
  find,
} from "@/assets/utils/table";

const tagsMap = {
  1: "danger",
  0: "success",
};
const baseUrl = process.env.VUE_APP_API_BASE_URL + "/";
export default {
  mounted() {
    this.getData();
  },
  watch: {
    $route(route) {
      this.query = Object.assign({}, this.query, route.query);
      this.getData();
    },
  },
  beforeDestroy() {
    this.source.cancel("自动取消ajax操作");
    clearTimeout(this.loadingTimer);
  },
  methods: {
    beforeUpload(file) {
      if (file.size / 1024 / 1024 > 200) {
        this.$message({
          message: "上传文件大小不能超过 200MB!",
          type: "error",
        });
        return false;
      }
      // 获取文件类型
      var test = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (test !== "xlsx" && test !== "xls") {
        this.$message({
          message: "上传文件只能是 zip、rar格式!",
          type: "warning",
        });
        return false;
      }
    },
    // 开启、关闭
    changePath(path) {
      this.pageInfo.list = path + "/list";
      this.pageInfo.del = path + "/delete";
      this.pageInfo.add = path + "/add";
      this.pageInfo.edit = path + "/edit";
      this.pageInfo.view = path + "/view";
    },
    beforeFecth() {
      return Promise.resolve();
    },
    // 表格接收数据前
    beforeRender(data) {
      return data;
    },
    // 表格接收数据后
    afterRender(data) {},
    // 删除动作发生后
    afterDel(data) {},
    // 默认拉取数据
    async getData() {
      try {
        await this.beforeFecth();
      } catch (error) {
        return;
      }
      this.tableData.loading = true;
      this.$post(this.pageInfo.list, this.query, {
        cancelToken: this.source.token,
      })
        .then(({ data }) => {
          this.tableData = this.beforeRender(
            Object.assign({}, this.tableData, data)
          );
          this.afterRender(this.tableData);
        })
        .catch((error) => {
          if (error.message == "自动取消ajax操作") return;
          this.$message.error(error.message);
        })
        .then((data) => {
          clearTimeout(this.loadingTimer);
          this.loadingTimer = setTimeout(() => {
            this.tableData.loading = false;
          }, 300);
        });
    },
    // 默认拉取数据
    async getTable() {
      try {
        await this.beforeFecth();
      } catch (error) {
        return;
      }
      this.tableData.loading = true;
      this.$post("/attendance/stat/summary", this.query, {
        cancelToken: this.source.token,
      })
        .then(({ data }) => {
          this.tableData = this.beforeRender(
            Object.assign({}, this.tableData, data)
          );
          this.afterRender(this.tableData);
        })
        .catch((error) => {
          if (error.message == "自动取消ajax操作") return;
          this.$message.error(error.message);
        })
        .then((data) => {
          clearTimeout(this.loadingTimer);
          this.loadingTimer = setTimeout(() => {
            this.tableData.loading = false;
          }, 300);
        });
    },
    // 复制一个数组或对象
    util_copy(data) {
      if (typeof data !== "object") return data;
      return JSON.parse(JSON.stringify(data));
    },
    _showAll(item) {
      let data = this.util_copy(item);
      data.isShowAll = true;
      this.util_update(item.id, data);
    },
    // 超长文本展开收起
    util_short(key, size) {
      return (row) => {
        let string = row[key] || "";
        if (string.length < size || row.isShowAll) return string;
        return (
          <span>
            {string.substr(0, 50) + "..."}
            <el-button
              size="mini"
              type="text"
              onClick={() => {
                this._showAll(row);
              }}
            >
              更多
            </el-button>
          </span>
        );
      };
    },
    // 从dict字段暴力取值，取不到则返回原值
    util_formatter(key, val) {
      try {
        return this.tableData.dict[key][val];
      } catch (error) {
        return val;
      }
    },
    // 通过id修改某条记录
    util_update(id, newData, idColumnName) {
      let table = this.tableData.data;
      let { index, data } = find(
        table,
        !idColumnName ? "id" : idColumnName,
        id
      );
      table.splice(index, 1, Object.assign({}, data, newData));
    },
    // 工具方法，把数字转化为字符串
    util_toString(data, array) {
      const dataCopy = Object.assign({}, data);
      for (var item in data) {
        dataCopy[item] =
          dataCopy[item] === undefined ? "" : dataCopy[item] + "";
      }
      return dataCopy;
    },
    util_formatterDate(time, fmt) {
      if (!time) return "";
      let date = new Date(Number(time));
      var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "[h|H]+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        S: date.getMilliseconds(), //毫秒
      };
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length == 1
              ? o[k]
              : ("00" + o[k]).substr(("" + o[k]).length)
          );
      return fmt;
    },
    util_getPrevMonthDate() {
      let date = new Date();
      var year = date.getFullYear();
      var month = date.getMonth();
      var day = date.getDate();
      if (month == 0) {
        //年份为0代表,是本年的第一月,所以不能减
        month = 11; //月份为上年的最后月份
        year--; //年份减1
        return new Date(year, month, day);
      }
      month--; //否则,只减去月份
      return new Date(year, month, day);
    },
    formatteSec(row, column, val) {
      return val ? (val / 60 / 60 / 24).toFixed(2) + "天" : "--";
    },
    // 格式化单元格数据
    formatter(row, column, val) {
      const content = formatter(this.tableData, column, val);
      return content == 0 ? (
        <p>{content ? content : "--"}</p>
      ) : content ? (
        content == "未处理" ? (
          <el-tag type={"danger"} size="mini">
            {content}
          </el-tag>
        ) : content == "已处理" ? (
          <el-tag type={"success"} size="mini">
            {content}
          </el-tag>
        ) : row.checkStatus == 1 || row.processStatus == 1 ? (
          row.subAddType == 1 && column.label.includes("分值") ? (
            <el-link type={"info"}>(+{content})</el-link>
          ) : row.subAddType == 2 && column.label.includes("分值") ? (
            <el-link type={"info"}>({-content})</el-link>
          ) : (
            <p>{content ? content : "--"}</p>
          )
        ) : row.checkStatus == 2 || row.processStatus == 2 ? (
          row.subAddType == 1 && column.label.includes("分值") ? (
            <el-link>+{content}</el-link>
          ) : row.subAddType == 2 && column.label.includes("分值") ? (
            <el-link>{-content}</el-link>
          ) : (
            <p>{content ? content : "--"}</p>
          )
        ) : row.subAddType == 1 && column.label.includes("分值") ? (
          <el-link>+{content}</el-link>
        ) : row.subAddType == 2 && column.label.includes("分值") ? (
          <el-link>{-content}</el-link>
        ) : (
          <p>{content ? content : "--"}</p>
        )
      ) : val ? (
        val
      ) : (
        "--"
      );
    },

    formatterYES(row, column, val) {
      const content = formatter(this.tableData, column, val);
      if (content) {
        if (val == "0") {
          return (
            <el-tag type={"danger"} size="mini">
              {content}
            </el-tag>
          );
        } else if (val == "1") {
          return (
            <el-tag type={"success"} size="mini">
              {content}
            </el-tag>
          );
        }
      } else {
        return val;
      }
    },

    formatterStatus(row, column, val) {
      const content = formatter(this.tableData, column, val);
      if (content) {
        if (val == "0") {
          return <el-tag size="mini">{content}</el-tag>;
        } else if (val == "1") {
          return (
            <el-tag type={"danger"} size="mini">
              {content}
            </el-tag>
          );
        } else if (val == "2") {
          return (
            <el-tag type={"success"} size="mini">
              {content}
            </el-tag>
          );
        }
      } else {
        return val;
      }
    },

    formatterDictLink(row, column, val) {
      const content = formatter(this.tableData, column, val);
      let underline = false;
      let type = "primary";
      if (val === 3) {
        type = "danger";
      }
      return content ? (
        <el-link
          type={type}
          underline={underline}
          onClick={() => {
            this.toDrawerMsg(row);
          }}
          size="mini"
        >
          {content}
        </el-link>
      ) : (
        val
      );
    },
    formatters(row, column, val) {
      if (val) {
        return val
          .split(",")
          .map((v) => {
            return formatter(this.tableData, column, v);
          })
          .join(",");
      }
      return "--";
    },
    formatterLink(row, column, val) {
      //const content = formatter(this.tableData, column-2, val);

      return (
        <el-link type="primary" href={val} target="_blank">
          {row.fileName}
        </el-link>
      );
      //return content;
      // return content ? <el-tag type={'info'} size='mini'>{content}</el-tag> : val
    },
    formatterString(row, column, val) {
      return formatter(this.tableData, column, val);
    },
    // 格式化单元格数据 0显示 0.00
    formatterAmount(row, column) {
      return formatterAmount(row, column);
    },
    // 格式化单元格数据钱单位里换算成元
    formatterMoney(row, column, val) {
      return ((val || 0) / 1000).toFixed(2);
    },
    // 查看天数
    formatterDay(row, column, val) {
      return val ? (
        <el-tag
          onClick={() => {
            this.handleCountDays(row, column, val);
          }}
        >
          {val}
        </el-tag>
      ) : (
        "不限额"
      );
    },
    // 格式化单元格数据
    formatterDate(row, column) {
      // console.log("date:",row,column)
      return formatterDate(row, column);
    },
    // 格式化单元格数据 只要年月日
    formatterDateOnly(row, column) {
      return formatterDateOnly(row, column);
    },
    // 格式化人员
    formaterPeople(row, column, val) {
      let info;
      if (val) {
        if (typeof val === "number") {
          info = (
            <el-tag type={"info"} size="mini">
              {this.util_formatter("assigneeList", val)}
            </el-tag>
          );
        } else {
          info = val.split(",").map((v) => {
            if (this.tableData.dict["assigneeList"][v] != undefined) {
              return (
                <el-tag type={"info"} size="mini">
                  {this.util_formatter("assigneeList", v)}
                </el-tag>
              );
            }
          });
        }
      } else {
        info = "--";
      }
      return info;
    },
    // 格式化员工类型
    formatterType(row, column, val) {
      const content = formatter(this.tableData, column, val);
      if (content) {
        if (val == "1") {
          return <el-tag size="mini">全职</el-tag>;
        } else if (val == "2") {
          return <el-tag size="mini">兼职</el-tag>;
        } else if (val == "3") {
          return <el-tag size="mini">实习</el-tag>;
        }
      } else {
        return val;
      }
    },
    // geshu
    // 格式化是否在政务中心
    formatterSource(row, column, val) {
      const content = formatter(this.tableData, column, val);
      if (content) {
        if (val == "1") {
          return <el-tag size="mini">是</el-tag>;
        } else if (val == "2") {
          return <el-tag size="mini">否</el-tag>;
        }
      } else {
        return val;
      }
    },

    // 格式化处理异常状态
    formattereErrorStatus(row, column, val) {
      const content = formatter(this.tableData, column, val);
      if (content) {
        return (
          <el-tag size="mini" type="danger">
            {this.util_formatter("errorStatus", val)}
          </el-tag>
        );
      } else {
        return val;
      }
    },
    // 格式化处理状态
    formattereDealStatus(row, column, val) {
      const content = formatter(this.tableData, column, val);
      if (content) {
        return (
          <el-tag size="mini">
            {this.util_formatter("processStatus", val)}
          </el-tag>
        );
      } else {
        return val;
      }
    },

    // 考勤组人数
    formatterGroupPerson(row, column, val) {
      const content = formatter(this.tableData, column, val);
      if (content) {
        return Number(row.personNum) + Number(row.personNumNo);
      } else {
        return val;
      }
    },
    // 考勤类型
    formatterattendType(row, column, val) {
      const content = formatter(this.tableData, column, val);
      if (content) {
        return <el-tag size="mini">{this.util_formatter("type", val)}</el-tag>;
      } else {
        return val;
      }
    },
    // 请假类型
    formatterLeaveType(row, column, val) {
      const content = formatter(this.tableData, column, val);
      if (content) {
        return (
          <el-tag size="mini">{this.util_formatter("leaveType", val)}</el-tag>
        );
      } else {
        return val;
      }
    },
    // 格式化图片展示
    formatterPic(row, column, val) {
      const content = formatter(this.tableData, column, val);
      if (content) {
        const suffix = `(bmp|jpg|png|tif|gif|pcx|tga|exif|fpx|svg|psd|cdr|pcd|dxf|ufo|eps|ai|raw|WMF|webp|jpeg)`;
        const regular = new RegExp(`.*\.${suffix}`);
        if (regular.test(val)) {
          return (
            // <el-image
            //   src={val.indexOf("http") == -1 ? baseUrl + val : val}
            //   preview-src-list={
            //     val.indexOf("http") == -1 ? [baseUrl + val] : [val]
            //   }
            //   style="width: 100px"
            // ></el-image>
            <filepReview src={val} />
          );
        } else {
          return <el-link type="primary">{val ? val : "--"}</el-link>;
        }
      } else {
        return val ? val : "--";
      }
    },

    // 考勤组格式
    formatterBanci(row, column, val) {
      const content = formatter(this.tableData, column, val);
      if (content) {
        // let string = row.attendanceTime.replace("、","<br>")
        return (
          <div>
            <div>
              <el-tag type="info">{row.restTime}</el-tag>
            </div>
            <div class="mt10" style="background:#ecf5ff;color:#409EFF">
              <p>{row.attendanceTime}</p>
            </div>
          </div>
        );
      } else {
        return val;
      }
    },
    // 多选表格行
    handleSelectionChange(val) {
      this.selection = val.map((i) => i.id);
    },
    // 当某一行被点击时会触发该事件
    handleRowClick(row, column, event) {},
    handleCellClick(row, column, event) {},
    // 合并表格行列
    handleSpanMethod() {},
    // 自定义表格排序
    handleSortChange() {},
    // 自定义索引号
    handleIndexMethod(index) {
      //prePageResult 每页条数
      // console.log("index:"+index)
      let size = this.tableData.pageInfo.prePageResult;
      let page = this.tableData.pageInfo.currPage;
      let count = parseInt(size) * (parseInt(page) - 1);
      return count + index + 1;
    },

    // 自定义表格选择行是否能勾选
    handleSelectableMethod(row, index) {
      return true;
    },

    // 设置单元行样式
    tableRowClassName() {},
    // 批量删除
    toBatchDel() {
      this.toDel(this.selection.join(","), true);
    },
    // 单个删除
    toDel(id, isBatch) {
      if (!id) {
        return this.$message.warning("请选中一条记录");
      }

      this.$get(this.pageInfo.del, { id: id })
        .then((res) => {
          this.$message.success(res.msg);
          // 更新数据
          if (isBatch) {
            // 批量删除，刷新页面
            this.getData();
          } else {
            let table = this.tableData.data;
            let { index } = find(table, "id", id);
            table.splice(index, 1);
            this.tableData.pageInfo.totalResult -= 1;
          }
          this.afterDel(id);
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },
    // 新增
    toAdd() {
      this.$router.push({
        path: this.pageInfo.add,
        query: this.tableConfig.addQuery,
      });
    },
    // 编辑
    toEdit(row, query) {
      this.$router.push({
        path: this.pageInfo.edit,
        query: Object.assign({}, { id: row.id }, query),
      });
    },
    // 查看
    toView(row, query) {
      // console.log(this.pageInfo.view);
      this.$router.push({
        path: this.pageInfo.view,
        query: Object.assign({}, { id: row.id }, query),
      });
    },
    // 导入
    toImport() {
      this.$router.push({
        path: this.pageInfo.importView,
        query: this.tableConfig.addQuery,
      });
    },
    // 导出
    toexport() {
      this.$router.push({
        path: this.pageInfo.importView,
        query: this.tableConfig.addQuery,
      });
    },
    // 返回
    toBack() {
      this.$router.push({
        path: this.pageInfo.back,
      });
    },
    // 开启、关闭
    open() {},
  },
  computed: {
    tableConfig() {
      return Object.assign({}, this.defaultConfig, this.config);
    },
    pageInfo() {
      const urls = {
        // 操作所需的url地址，和url同路径
        list:
          this.$route.path.indexOf("/attendance/stat/list") == 0
            ? "/attendance/stat/listExt"
            : this.$route.path,
        edit: this.$route.path.replace("/list", "/edit"),
        save: this.$route.path.replace("/list", "/save"),
        del: this.$route.path.replace("/list", "/delete"),
        add: this.$route.path.replace("/list", "/add"),
        view: this.$route.path.replace("/list", "/view"),
        importView: this.$route.path.replace("/list", "/importView"),
        exclude: this.$route.path.replace("/list", "/list/exclude"),
      };
      return Object.assign({}, urls, this.urls);
    },
  },
  data() {
    return {
      source: axios.CancelToken.source(),
      loadingTimer: null,
      query: this.$route.query, // url-query参数
      selection: [], // 表格内置的多选
      urls: {},
      toString: [],
      defaultConfig: {
        search: [], // 头部搜索配置
        columns: [], // 表格列信息配置
        addQuery: {}, // 新增按钮携带的参数
        buttons: [], // 增加查询区域自定义操作按钮,格式：[{label:'按钮显示名称',isShow:是否显示true/false,loading:true/false,type:'类型',icon:'图标',method:function(){}}]
        methods: {
          handleSelectionChange: this.handleSelectionChange,
          handleRowClick: this.handleRowClick,
          handleCellClick: this.handleCellClick,
          tableRowClassName: this.tableRowClassName,
          handleSpanMethod: this.handleSpanMethod,
          handleSortChange: this.handleSortChange,
          handleIndexMethod: this.handleIndexMethod,
          handleSelectableMethod: this.handleSelectableMethod,
          edit: this.toEdit,
          add: this.toAdd,
          del: this.toBatchDel,
          back: this.toBack,
          importView: this.toImport,
          refresh: this.getData,
        },
      },
      tableData: {
        // 表格数据
        loading: true, // ajax请求状态
        dict: {},
        result: [],
        pageInfo: {},
      },
    };
  },
};
