<template>
  <div>
    <div class="table-header table-div el-scrollbar">
      <ListLayout :table-columns="tableColumns">
        <div slot="search" style="margin-top: 5px">
          <!--这里放顶部搜索-->
          <!-- 搜索部分开始 -->
          <el-form
            label-width="90px"
            :inline="true"
            :model="page"
            class="search-form"
            :size="$store.getters.size"
          >
            <el-form-item>
              <el-select
                v-model="page.params.companyId"
                remote
                filterable
                :remote-method="companyOrginQuery"
                clearable
                placeholder="企业名称"
                @keyup.enter.native="getByPage"
              >
                <el-option
                  v-for="item in queryCompanyList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-date-picker
                v-model="page.params.snapshotTime"
                type="date"
                clearable
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="选择快照日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-form>

          <!-- 搜索部分结束 -->
        </div>

        <el-row slot="button-group" style="margin-top: 5px">
          <el-col :span="12" class="tal">
            <el-button
              class="group-item"
              :size="$store.getters.size"
              type="primary"
              @click="toOutPut"
              ><svg-icon icon-class="icondaochu" /> 导出</el-button
            >
          </el-col>
          <el-button
            type="primary"
            :size="$store.getters.size"
            icon="el-icon-search"
            @click="search"
            >查询</el-button
          >
          <el-button
            :size="$store.getters.size"
            icon="el-icon-refresh"
            type="info"
            @click="page.params = {}"
            >重置</el-button
          >
        </el-row>

        <div slot="table">
          <!--这里放表格和分页-->
          <!-- 列表开始 -->
          <el-table
            :data="dataPage.list"
            fit
            :max-height="tableHeight"
            stripe
            style="width: 100%"
            :size="$store.getters.size"
            @sort-change="sortHandler"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="序号" type="index" />
            <template v-for="(item, index) in tableColumns">
              <el-table-column
                v-if="item.show"
                :key="index"
                :fixed="item.fixed"
                :align="item.align"
                :show-overflow-tooltip="true"
                :min-width="item.minWidth"
                :width="item.width"
                :prop="item.prop"
                :sortable="item.sortable"
                :label="item.label"
                :formatter="item.render"
              />
            </template>
          </el-table>
          <!-- 列表结束 -->

          <!-- 分页组件开始 -->
          <div class="page-div">
            <el-pagination
              :current-page="page.currentPage"
              :page-sizes="[10, 15, 20, 30]"
              :page-size="page.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="page.totalCount"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
          <!-- 分页组件结束 -->
        </div>
      </ListLayout>

      <!-- 添加弹窗 -->
      <el-dialog
        v-el-drag-dialog
        title="添加"
        :visible.sync="addDialog"
        width="55%"
      >
        <OilCompanyAccountAdd
          @getByPage="getByPage"
          @closeDialog="closeDialog"
        />
      </el-dialog>

      <!-- 导出弹窗 -->
      <!-- <el-dialog
        v-el-drag-dialog
        title="导出"
        :visible.sync="outPutDialog"
        width="55%"
      >
        <OilCompanyAccountOutput @getByPage="getByPage" @closeDialog="closeDialog" />
      </el-dialog> -->
      <el-drawer
        title="导出"
        :visible.sync="outPutDialog"
        width="20%"
        size="40%"
        direction="ltr"
      >
        <el-form label-width="75px" size="small">
          <el-row class="box_daochu">
            <el-col :span="24">
              <el-form-item label="导出方式">
                <el-select v-model="output.outputType" style="width: 100%">
                  <el-option label="导出选中" :value="1" />
                  <!-- <el-option label="导出本页" :value="2" /> -->
                  <el-option label="条件导出" :value="3" />
                  <!-- <el-option label="eseyExcel条件导出" :value="4" /> -->
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item v-if="output.outputType !== 4">
                <div style="color: red">
                  <span v-if="output.outputType === 1"
                    >当前选中数据 {{ multipleSelection.length }} 条</span
                  >
                  <span v-if="output.outputType === 2"
                    >本页数据 {{ dataPage.list.length }} 条</span
                  >
                  <span v-if="output.outputType === 3"
                    >条件导出将直接使用页面搜索条件进行数据过滤</span
                  >
                </div>
              </el-form-item>
            </el-col>
            <el-col
              v-if="output.outputType === 3 || output.outputType === 4"
              :span="12"
            >
              <el-form-item label="开始页">
                <el-input v-model="output.startPage" />
              </el-form-item>
            </el-col>
            <el-col
              v-if="output.outputType === 3 || output.outputType === 4"
              :span="12"
            >
              <el-form-item label="结束页">
                <el-input v-model="output.endPage" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item>
                <el-button type="primary" @click="outputData">导出</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-drawer>

      <!-- 导入弹窗 -->
      <el-dialog
        v-el-drag-dialog
        title="导入"
        :visible.sync="importDialog"
        width="55%"
      >
        <OilCompanyAccountImport
          @getByPage="getByPage"
          @closeDialog="closeDialog"
        />
      </el-dialog>

      <!-- 修改弹窗 -->
      <el-dialog
        v-el-drag-dialog
        title="修改"
        :visible.sync="updateDialog"
        width="55%"
      >
        <OilCompanyAccountUpdate
          :oil-company-account="oilCompanyAccount"
          @getByPage="getByPage"
          @closeDialog="closeDialog"
        />
      </el-dialog>

      <!-- 详情抽屉 -->
      <el-drawer
        size="50%"
        title="详情"
        class="table-detail-drawer"
        :visible.sync="showTableDrawer"
        direction="ltr"
      >
        <OilCompanyAccountInfo v-if="showTableDrawer" :company-id="companyId" />
      </el-drawer>

      <!-- 添加充值 -->
      <el-dialog
        v-el-drag-dialog
        title="充值"
        :visible.sync="rechargeDialog"
        width="55%"
      >
        <OilCompanyAccountReverse
          v-if="rechargeDialog"
          :oil-company-account="oilCompanyAccount"
          @getByPage="getByPage"
          @closeDialog="closeDialog"
        />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import oilCompanyAccountApi from "@/api/mongoDB/mongoSnapShot";
import { mapGetters } from "vuex";
import oilCompanyInfoApi from "@/api/user/oilCompanyInfo";
import sysCustomerInfoApi from "@/api/user/sysCustomerInfo";

export default {
  components: {},
  data() {
    return {
      rechargeDialog: false, // 充值
      queryCompanyList: [],
      multipleSelection: [], // 选择表格数据集合
      importDialog: false, // 导入弹窗
      outPutDialog: false, // 导出弹窗
      showTableDrawer: false,
      output: {
        outputType: 1, // 导出方式，1导出选中，2导出本页，3条件导出，4导出全部
        startPage: 1, // 导出开始页
        endPage: 1, // 导出结束页
        pageSize: 20, // 每页条数
      },
      page: {
        pageSize: 20, // 每页显示条数
        currentPage: 1, // 默认页
        params: {
          snapshotTime: new Date(),
        }, // 查询参数
        sorted: {
          snapshotTime: "desc",
        },
        columns: [],
      },
      tableHeight: document.documentElement.clientHeight - 300 - 60,
      filters: this.$options.filters,
      dataPage: {
        // 分页显示page
        pageSize: 20, // 每页显示条数
        currentPage: 1, // 默认页
        params: {
          // 查询参数
        },
        sorted: {},
      },
      userList: "",
      tableColumns: [
        // { prop: 'id', sortable: 'custom', label: '主键', show: true, render: (row, column, cell) => {
        //   return cell
        // } },
        {
          prop: "snapshotTime",
          label: "快照日期",
          width: 180,
          show: true,
          render: (row, column, cell) => {
            return cell;
          },
        },
        {
          prop: "companyName",
          sortable: "custom",
          label: "企业名称",
          width: 300,
          show: true,
          render: (row, column, cell) => {
            if (row.accountState === 1) {
              return (
                <div style="display:flex;align-items: center;">
                  <el-tag type="" effect="dark">
                    启用
                  </el-tag>
                  <div>
                    <span style="padding-left:8px;">{cell}</span>
                    <br />
                  </div>
                </div>
              );
            } else if (row.accountState === 0) {
              return (
                <div style="display:flex;align-items: center;">
                  <el-tag type="info" effect="dark">
                    禁用
                  </el-tag>
                  <span style="padding-left:8px;">{cell}</span>
                  <br />
                </div>
              );
            } else if (row.accountState === -1) {
              return (
                <div style="display:flex;align-items: center;">
                  <el-tag type="info" effect="dark">
                    冻结
                  </el-tag>
                  <span style="padding-left:8px;">{cell}</span>
                  <br />
                </div>
              );
            }
          },
        },
        {
          prop: "totalBalance",
          align: "right",
          label: "公司总余额",
          width: 120,
          show: true,
          render: (row, column, cell) => {
            return cell;
          },
        },
        {
          align: "left",
          label: "司机油卡余额",
          width: 130,
          show: true,
          render: (row, column, cell) => {
            return (
              <div>
                <span>外:{row.outCountBalance}</span>
                <br />
                <span>自:{row.inCountBalance}</span>
              </div>
            );
          },
        },
        {
          prop: "balance",
          label: "账户总余额",
          width: 120,
          show: true,
          render: (row, column, cell) => {
            return cell;
          },
        },
        {
          prop: "rechargeBalance",
          label: "充值余额",
          width: 80,
          show: true,
          render: (row, column, cell) => {
            return cell;
          },
        },
        {
          prop: "chargeRechargeBalance",
          label: "赊销充值余额",
          width: 120,
          show: true,
          render: (row, column, cell) => {
            return cell;
          },
        },
        {
          prop: "rechargeRebateBalance",
          label: "充值返利余额",
          width: 120,
          show: true,
          render: (row, column, cell) => {
            return cell;
          },
        },
        {
          prop: "consumeRebateBalance",
          label: "消费返利余额",
          width: 120,
          show: true,
          render: (row, column, cell) => {
            return cell;
          },
        },
        {
          prop: "totalChargeAmount",
          label: "赊销待还",
          show: true,
          render: (row, column, cell) => {
            return cell;
          },
        },
        {
          prop: "updateTime",
          width: 170,
          label: "修改时间",
          show: true,
          render: (row, column, cell) => {
            return cell;
          },
        },
      ],
      valColumn: [
        "snapshotTime",
        "companyName",
        "accountState",
        "totalBalance",
        "outCountBalance",
        "inCountBalance",
        "balance",
        "rechargeBalance",
        "chargeRechargeBalance",
        "rechargeRebateBalance",
        "consumeRebateBalance",
        "totalChargeAmount",
        "updateTime",
      ],
      headers: [
        "快照日期",
        "企业名称",
        "启用状态",
        "公司总余额",
        "外请司机油卡余额",
        "自营司机油卡余额",
        "账户总余额",
        "充值余额",
        "赊销充值余额",
        "充值返利余额",
        "消费返利余额",
        "赊销待还",
        "修改时间",
      ],
      addDialog: false, // 添加弹窗
      updateDialog: false, // 修改弹窗
      oilCompanyAccount: {},
      companyId: {},
    };
  },
  computed: {
    ...mapGetters(["sysUserList"]),
  },
  created() {
    this.getByPage();
    // 增加监听事件，窗口变化时得到高度。
    window.addEventListener("resize", this.getHeight, false);
  },
  methods: {
    companyOrginQuery(value) {
      // 远程搜索
      if (value) {
        oilCompanyInfoApi.getLikeByName({ name: value }).then((res) => {
          this.queryCompanyList = res.data;
        });
      }
    },
    async outputData() {
      // 导出数据
      let tmpData = [];
      const status = this.output.outputType;
      if (status === 1) {
        tmpData = this.multipleSelection;
        this.ImportExcel(tmpData);
      } else if (status === 3 || status === 2) {
        const endIndex =
          (parseInt(this.output.endPage) +
            1 -
            parseInt(this.output.startPage)) *
          parseInt(this.output.pageSize);
        const searchParam = { ...this.page };
        searchParam.pageSize = endIndex;
        searchParam.currentPage = this.output.startPage;
        const res = await oilCompanyAccountApi.getCompanyAccountByPage(
          searchParam
        );
        tmpData = res.data.list;
        this.ImportExcel(tmpData);
      } else if (status === 4) {
        const endIndex =
          (parseInt(this.output.endPage) +
            1 -
            parseInt(this.output.startPage)) *
          parseInt(this.output.pageSize);
        const searchParam = { ...this.page };
        searchParam.pageSize = endIndex;
        searchParam.currentPage = this.output.startPage;
        console.time();
        oilCompanyAccountApi.export2Web(searchParam).then((res) => {
          this.tableHeight = this.tableHeight + this.sHeight;
          // console.log("123")
          // console.log(res)
          const link = document.createElement("a");
          // 创建Blob对象，设置文件类型
          const blob = new Blob([res], { type: "application/vnd.ns-excel" }); // MIME类型
          link.href = URL.createObjectURL(blob); // 创建URL
          link.setAttribute("download", decodeURI(Date.now() + ".xlsx")); // 设置下载文件名称
          link.click(); // 下载文件
          document.body.appendChild(link);
          console.timeEnd();
          this.$message.success("导出成功");
          URL.revokeObjectURL(link.href); // 释放内存
        });
      } else {
        const cs = await oilCompanyAccountApi.getCount();
        const dataCount = cs.data;

        const searchParam = {
          currentPage: 1,
          pageSize: dataCount,
        };
        const res = await oilCompanyAccountApi.getCompanyAccountByPage(
          searchParam
        );
        tmpData = res.data.list;
        this.ImportExcel(tmpData);
      }
    },
    ImportExcel(tmpData) {
      import("@/vendor/Export2Excel").then((excel) => {
        const data = this.formatJson(this.valColumn, tmpData);
        excel.export_json_to_excel({
          header: this.headers,
          data: data,
          autoWidth: true,
          bookType: "xlsx",
        });
        this.$message.success("导出成功");
      });
    },
    formatJson(filterVal, jsonData) {
      // 处理数据
      // console.log('filterVal：' + JSON.stringify(filterVal))
      // console.log('jsonData：' + JSON.stringify(jsonData))
      return jsonData.map((v) =>
        filterVal.map((j) => {
          if (j.indexOf(".") < 0) {
            return v[j];
          }
          const keyArr = j.split(".");
          let data = v[keyArr[0]];
          for (var i = 1; i < keyArr.length; i++) {
            if (data) {
              data = data[keyArr[i]];
            }
          }
          return data;
        })
      );
    },
    userRemoteMethod(value) {
      // 远程搜索
      if (value) {
        sysCustomerInfoApi.liekQuery(value).then((res) => {
          this.userList = res.data;
        });
      }
    },
    handleSelectionChange(val) {
      // 选择表格数据
      this.multipleSelection = val;
    },
    toForbid() {
      // 禁用
      if (!this.multipleSelection || this.multipleSelection.length < 1) {
        this.$message.error("请选择需要操作的数据");
        return;
      }
      this.multipleSelection.forEach((item) => {
        item.accountState = "0";
      });
      oilCompanyAccountApi
        .updateAccountState(this.multipleSelection)
        .then((res) => {
          if (res.code === 20000) {
            this.$message.success(res.msg);
          }
          this.getByPage();
        });
    },
    toStartUsing() {
      // 启用
      if (!this.multipleSelection || this.multipleSelection.length < 1) {
        this.$message.error("请选择需要操作的数据");
        return;
      }
      this.multipleSelection.forEach((item) => {
        item.accountState = "1";
      });
      oilCompanyAccountApi
        .updateAccountState(this.multipleSelection)
        .then((res) => {
          if (res.code === 20000) {
            this.$message.success(res.msg);
          }
          this.getByPage();
        });
    },
    toFreeze() {
      // 冻结
      if (!this.multipleSelection || this.multipleSelection.length < 1) {
        this.$message.error("请选择需要操作的数据");
        return;
      }
      this.multipleSelection.forEach((item) => {
        item.accountState = "-1";
      });
      oilCompanyAccountApi
        .updateAccountState(this.multipleSelection)
        .then((res) => {
          if (res.code === 20000) {
            this.$message.success(res.msg);
          }
          this.getByPage();
        });
    },
    toImport() {
      // 导入
      this.importDialog = true;
    },
    toOutPut() {
      // 导出
      this.outPutDialog = true;
    },
    handleDetail(id) {
      // 查看行 详情
      oilCompanyAccountApi.get(id).then((res) => {
        this.oilCompanyAccount = res.data;
        this.companyId.companyId = res.data.companyId;
        this.showTableDrawer = true;
      });
    },
    getHeight() {
      // 获取浏览器高度并计算得到表格所用高度。
      this.tableHeight = document.documentElement.clientHeight - 300 - 60;
    },
    search() {
      // 搜索
      this.page.currentPage = 1;
      this.getByPage();
    },
    toggleSearchAdvance() {
      this.searchAdvice = !this.searchAdvice;
    },
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.getByPage();
    },
    handleCurrentChange(val) {
      this.page.currentPage = val;
      this.getByPage();
    },
    sortHandler(column) {
      // 排序查询
      console.log(column);
      const key = column.prop;
      const value = column.order;
      this.page.sorted = {};
      this.page.sorted[key] = value;
      this.getByPage();
    },
    toAdd() {
      // 跳转到添加
      this.oilCompanyAccount = {};
      this.addDialog = true;
    },
    toUpdate(id) {
      // 跳转到更新
      oilCompanyAccountApi.get(id).then((res) => {
        this.oilCompanyAccount = res.data;
        this.updateDialog = true;
      });
    },
    toRecharge(id) {
      // 跳转到充值
      oilCompanyAccountApi.get(id).then((res) => {
        this.oilCompanyAccount = res.data;
        this.rechargeDialog = true;
      });
    },
    toDelete(id) {
      // 删除
      this.$confirm("确定删除?", "提示", { type: "error" }).then(() => {
        oilCompanyAccountApi.deleteById(id).then((res) => {
          this.$message.success(res.msg);
          this.getByPage();
        });
      });
    },
    getByPage() {
      // 分页查询
      this.addDialog = false;
      oilCompanyAccountApi.getCompanyAccountByPage(this.page).then((res) => {
        this.dataPage = res.data;
        this.page.totalCount = this.dataPage.totalCount;
        this.page.totalPage = this.dataPage.totalPage;
      });
    },
    closeDialog() {
      this.addDialog = false;
      this.updateDialog = false;
      this.rechargeDialog = false;
    },
  },
};
</script>

<style scoped>
.handle-button-group {
  margin-bottom: 10px;
}

.page-div {
  /* position: fixed; */
  background: #fff;
  bottom: 0rem;
  z-index: 4;
  min-width: 100%;
}
</style>
