<template>
  <div class="div_main">
    <div v-show="true">
      <div class="div_search">
        <el-form :inline="true" ref="ref_searchform" :label-width="'80px'">
          <div>
            <el-form-item
              v-for="item in searchParams"
              :key="'serach' + item.keyName"
              :label="item.field"
              :prop="item.keyName"
            >
              <template v-if="item.type == 'input'">
                <el-input
                  v-model="item.value"
                  class="item_width_1"
                  size="small"
                  clearable
                  :placeholder="item.placeholder || '请输入'"
                >
                </el-input>
              </template>
              <template v-else-if="item.type == 'select'">
                <el-select
                  v-model="item.value"
                  :placeholder="item.placeholder || '请选择'"
                  size="small"
                  clearable
                  class="item_width_2"
                >
                  <el-option
                    v-for="item in item.optionList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-form-item>

            <el-button
              style="margin-left: 30px"
              size="small"
              class="diy-button--search"
              @click="handleSearch"
              >查询</el-button
            >
            <el-button
              style="margin-left: 10px"
              size="small"
              class="diy-button--reset"
              @click="resetSearch"
              >重置</el-button
            >
          </div>
        </el-form>
      </div>

      <div class="div_table">
        <div class="div_btn">
          <el-button
            class="diy-button--add"
            v-if="addUrl"
            size="small"
            @click="handleAdd"
            >新增</el-button
          >

          <!-- <el-button
            @click="handleExport"
            class="diy-button--reset"
            size="small"
            >导出</el-button
          > -->
        </div>

        <el-table
          :data="tableData"
          border
          :header-cell-style="{ background: '#2195FE', color: '#FFFFFF' }"
          class="table"
          style="width: 100%"
          :height="maxTableHeight"
        >
          <template v-for="item in tableParams" :prop="item.keyName">
            <el-table-column
              v-if="item.type == 'no'"
              :key="'table' + item.keyName"
              :label="item.field"
              fixed="left"
              type="index"
              align="center"
              width="50"
            />

            <el-table-column
              :key="'table' + item.keyName"
              v-else-if="item.type == 'text'"
              :prop="item.keyName"
              :label="item.field"
              align="center"
              :width="item.width || ''"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
          </template>

          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="200"
          >
            <template slot-scope="scope">
              <el-button
                @click="handleWatch(scope.row)"
                type="text"
                size="small"
                class=".div-table-button--detail"
                >查看</el-button
              >
              <el-button
                v-if="editUrl"
                @click="handleEdit(scope.row)"
                type="text"
                size="small"
                class="div-table-button--edit"
                >编辑</el-button
              >
              <el-popconfirm
                v-if="delUrl"
                title="删除之后无法回复，确认删除？"
                @onConfirm="handleDelete(scope.row, scope.$index)"
                @confirm="handleDelete(scope.row, scope.$index)"
              >
                <el-button
                  slot="reference"
                  type="text"
                  size="small"
                  style="margin-left: 10px"
                  class="div-table-button--delete"
                  >删除</el-button
                >
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <div>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="pageNo"
            :page-sizes="[20, 50, 100, 200]"
            :page-size="parseInt(pageSize)"
            layout="sizes, prev, pager, next, total"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 修改弹出框 -->
    <el-dialog
      v-if="formShow"
      :visible.sync="formShow"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="formTitle"
      width="850px"
      top="5vh"
      class="dialog-h"
      @closed="handleClose"
    >
      <edit-form
        ref="eleEditForm"
        :formId="formId"
        :formType="formType"
        :editParams="editParams"
        @close="handleClose"
        @afterEdit="handleEditSuccess"
      ></edit-form>
    </el-dialog>
  </div>
</template>

<script>
import { requestPost } from "@/js/dai/request";
import { mapGetters } from "vuex";
import axios from "axios";
import editForm from "./cpts/edit";

export default {
  components: { editForm },

  props: {
    searchParams: {
      type: Array,
      default: () => [],
    },
    searchUrl: {
      type: String,
      default: "",
    },

    tableParams: {
      type: Array,
      default: () => [],
    },

    tableUrl: {
      type: String,
      default: "",
    },

    addUrl: {
      type: String,
      default: "",
    },
    editUrl: {
      type: String,
      default: "",
    },
    delUrl: {
      type: String,
      default: "",
    },
    exportUrl: {
      type: String,
      default: "",
    },

    editParams: {
      type: Array,
      default: () => [],
    },
  },

  data() {
    return {
      tableData: [],

      pageNo: 1,
      pageSize: window.localStorage.getItem("pageSize") || 20,
      total: 1,

      formId: "",
      formShow: false,
      formTitle: "详情",
      formType: "", // 列表list 新增add  修改edit 详情info
    };
  },

  computed: {
    maxTableHeight() {
      return this.$store.state.inIframe
        ? this.clientHeight - 410 + this.iframeHeigh
        : this.clientHeight - 410;
    },
    ...mapGetters(["clientHeight", "iframeHeight"]),
  },

  watch: {},

  mounted() {
    console.log(this.$store.state);
    this.user = this.$store.state.user;

    this.agencyId = this.user.agencyId;

    this.iniSearchData();

    this.getTableData();
  },
  methods: {
    iniSearchData() {
      const { searchParams } = this;
      searchParams.forEach((item, index) => {
        if (item.type == "select") {
          if (item.optionUrl) {
            this.getFmOptions(
              index,
              item.optionUrl,
              item.optionUrlParams || {}
            );
          }
        }
      });
    },

    async getFmOptions(index, url, params) {
      const { data, code, msg } = await requestPost(url, {
        ...params,
      });

      if (code === 0) {
        this.searchParams[index].optionList = data || [];
      } else {
        this.$message.error("请求检索基础数据失败！");
      }
    },

    handleSearch(val) {
      this.pageNo = 1;

      this.getTableData();
    },

    async handleExport() {
      const { exportUrl: url } = this;
      if (!url) return;

      const { pageSize, pageNo } = this;

      axios({
        url: window.SITE_CONFIG["apiURL"] + url,
        method: "post",
        data: {
          pageSize,
          pageNo,
          ...this.computeFmData(),
        },
        responseType: "blob",
      })
        .then((res) => {
          let fileName = window.decodeURI(
            res.headers["content-disposition"].split(";")[1].split("=")[1]
          );
          console.log("filename", fileName);
          let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
          var url = window.URL.createObjectURL(blob);
          var aLink = document.createElement("a");
          aLink.style.display = "none";
          aLink.href = url;
          aLink.setAttribute("download", fileName);
          document.body.appendChild(aLink);
          aLink.click();
          document.body.removeChild(aLink); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        })
        .catch((err) => {
          console.log("获取导出情失败", err);
          return this.$message.error("网络错误");
        });
    },

    handleAdd() {
      this.formType = "add";
      this.formTitle = "新增";
      this.formShow = true;
    },

    handleWatch(row) {
      this.formType = "watch";
      this.formId = row.icServiceOrgId;
      this.formTitle = "查看";
      this.formShow = true;
    },

    handleEdit(row) {
      this.formType = "edit";
      this.formId = row.icServiceOrgId;
      this.formTitle = "编辑";
      this.formShow = true;
    },

    handleClose() {
      this.formShow = false;
    },

    handleEditSuccess() {
      this.handleClose();
      this.getTableData();
    },

    async handleDelete(rowData, rowIndex) {
      console.log(rowData, rowIndex);
      const { delUrl: url } = this;
      if (!url) return;

      const { tableData } = this;

      const { data, code, msg } = await requestPost(url, {
        icServiceOrgId: tableData[rowIndex].icServiceOrgId,
      });

      if (code === 0) {
        this.$message.success("删除成功！");
        this.getTableData();
      } else {
        this.$message.error("操作失败！");
      }
    },

    computeFmData() {
      let fmData = {};
      this.searchParams.forEach((item) => {
        fmData[item.keyName] = item.value;
      });
      return fmData;
    },

    async getTableData() {
      const { tableUrl: url, searchParams } = this;
      if (!url) return;

      const { pageSize, pageNo } = this;
      const { data, code, msg } = await requestPost(url, {
        pageSize,
        pageNo,
        ...this.computeFmData(),
      });

      if (code === 0) {
        this.total = data.total || 0;
        this.tableData = data.list
          ? data.list.map((item) => {
              return item;
            })
          : [];
      } else {
        this.$message.error(msg);
      }
    },

    handleSizeChange(val) {
      this.pageSize = val;
      window.localStorage.setItem("pageSize", val);
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.pageNo = val;
      this.getTableData();
    },

    resetSearch() {
      this.searchParams.forEach((item) => {
        item.value = "";
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/scss/buttonstyle.scss";
@import "@/assets/scss/modules/management/list-main.scss";
@import "@/assets/scss/modules/shequzhili/event-info.scss";
</style>
