<template>
  <div>
    <el-row v-if="isShow">
      <el-col :span="5">
        <basic-container>
          <avue-tree
            :option="treeOption"
            :data="treeData"
            @node-click="nodeClick"
          />
        </basic-container>
      </el-col>
      <el-col :span="19">
        <basic-container>
          <avue-crud
            :option="option"
            :search.sync="search"
            :table-loading="loading"
            :data="data"
            ref="crud"
            v-model="form"
            @row-del="rowDel"
            @row-update="rowUpdate"
            @row-save="rowSave"
            :before-open="beforeOpenE"
            :page.sync="page"
            @search-change="searchChange"
            @search-reset="searchReset"
            @selection-change="selectionChange"
            @current-change="currentChange"
            @size-change="sizeChange"
            @refresh-change="refreshChange"
            @on-load="onLoad"
          >
            <template slot="menuLeft">
              <el-button
                type="primary"
                size="small"
                icon="el-icon-bottom"
                @click="excelBox = true"
                >导入
              </el-button>
              <el-button
                icon="el-icon-printer"
                size="small"
                type="primary"
                @click.stop="openReport()"
                >报表打印
              </el-button>
              <el-button
                type="warning"
                size="small"
                :disabled="selectionList.length == 0"
                icon="el-icon-delete"
                @click="batchDelete"
                >批量删除
              </el-button>
            </template>
            <template slot-scope="scope" slot="corpId">
              <span>{{ scope.row.corpName }}</span>
            </template>
            <template slot-scope="scope" slot="menu">
              <!--            <el-button-->
              <!--                type="text"-->
              <!--                icon="el-icon-view"-->
              <!--                size="small"-->
              <!--                @click.stop="beforeOpenPage(scope.row, scope.index)"-->
              <!--            >查看-->
              <!--            </el-button>-->
              <el-button
                type="text"
                icon="el-icon-edit"
                size="small"
                @click.stop="editOpen(scope.row, scope.index)"
                >编辑
              </el-button>
              <el-button
                type="text"
                icon="el-icon-delete"
                size="small"
                @click.stop="rowDel(scope.row, scope.index)"
                >删除
              </el-button>
              <!--            <el-button-->
              <!--                type="text"-->
              <!--                icon="el-icon-delete"-->
              <!--                size="small"-->
              <!--            >下架-->
              <!--            </el-button>-->
            </template>
            <template slot="cnameIntSearch">
              <el-input
                placeholder="请输入 产品名称"
                size="small"
                v-model="search.cnameInt"
              ></el-input>
            </template>
          </avue-crud>
          <el-dialog
            title="导入产品"
            append-to-body
            :visible.sync="excelBox"
            :close-on-click-modal="false"
            width="555px"
          >
            <avue-form
              :option="excelOption"
              v-model="excelForm"
              :upload-after="uploadAfter"
            >
              <template slot="excelTemplate">
                <el-button type="primary" @click="derivation">
                  点击下载<i class="el-icon-download el-icon--right"></i>
                </el-button>
              </template>
            </avue-form>
            <p style="text-align: center;color: #DC0505">
              温馨提示 第一次导入时请先下载模板
            </p>
          </el-dialog>
        </basic-container>
      </el-col>
      <report-dialog
        :switchDialog="switchDialog"
        @onClose="onClose()"
      ></report-dialog>
    </el-row>

    <detail-page
      ref="detail"
      @goBack="goBack"
      :detailData="detailData"
      v-else
    ></detail-page>
  </div>
</template>
<script>
import {
  getList,
  getUser,
  getUserPlatform,
  remove,
  updatePlatform,
  add,
  grant,
  getDeptLazyTree,
  getDeptTree
} from "@/api/basicData/commodityType";
import { getRoleTree } from "@/api/system/role";
import { mapGetters } from "vuex";
import website from "@/config/website";
import { getToken } from "@/util/auth";
import option from "./configuration/mainList.json";
import detailPage from "./detailsPageEdit";
import reportDialog from "@/components/report-dialog/main";
export default {
  components: {
    reportDialog,
    detailPage
  },
  data() {
    return {
      form: {},
      search: {},
      switchDialog: false,
      roleBox: false,
      excelBox: false,
      platformBox: false,
      initFlag: true,
      selectionList: [],
      query: {},
      loading: true,
      platformLoading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      platformPage: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      init: {
        roleTree: [],
        deptTree: []
      },
      props: {
        label: "title",
        value: "key"
      },
      roleGrantList: [],
      roleTreeObj: [],
      treeDeptId: "",
      treeData: [],
      treeOption: {
        nodeKey: "id",
        lazy: true,
        treeLoad: function(node, resolve) {
          const parentId = node.level === 0 ? 0 : node.data.id;
          getDeptLazyTree(parentId).then(res => {
            resolve(
              res.data.data.map(item => {
                return {
                  ...item,
                  leaf: !item.hasChildren
                };
              })
            );
          });
        },
        addBtn: false,
        menu: false,
        size: "small",
        props: {
          labelText: "标题",
          label: "title",
          value: "value",
          children: "children"
        }
      },
      option: option,
      data: [],
      platformQuery: {},
      platformSelectionList: [],
      platformData: [],
      platformForm: {},
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24
          },
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data"
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/blade-client/goodsdesc/import-desc-info"
          }
        ]
      },
      isShow: true,
      detailData: {}
    };
  },
  mounted() {
    option.height = window.innerHeight - 255;
  },
  methods: {
    derivation() {
      window.open(
        `/api/blade-client/goodsdesc/export-template-info?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    uploadAfter(res, done, loading, column) {
      window.console.log(column);
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    nodeClick(data) {
      this.treeDeptId = data.id;
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    initData(tenantId) {
      getDeptTree().then(res => {
        const column = this.findObject(this.option.column, "goodsTypeId");
        column.dicData = res.data.data;
      });
    },
    submitRole() {
      const roleList = this.$refs.treeRole.getCheckedKeys().join(",");
      grant(this.ids, roleList).then(() => {
        this.roleBox = false;
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.onLoad(this.page);
      });
    },
    rowSave(row, done, loading) {
      row.goodsTypeId = row.goodsTypeId.join(",");
      add(row).then(
        () => {
          this.initFlag = false;
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      row.goodsTypeId = row.goodsTypeId.join(",");
      add(row).then(
        () => {
          this.initFlag = false;
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    //批量删除
    batchDelete() {
      this.$confirm("确定批量删除数据?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let batchDeleteList = this.selectionList.map(item => {
          return item.id;
        });
        remove(batchDeleteList.join(",")).then(res => {
          if (res.data.success) {
            this.$message.success("删除成功!");
            this.refreshChange();
          }
        });
      });
    },
    //查看跳转页面
    beforeOpenPage(row, index) {
      this.detailData = {
        id: row.id,
        seeDisabled: true
      };
      this.isShow = false;
    },
    //新增跳转页面
    beforeOpenE(row, index) {
      this.detailData = {
        goodsTypeId: this.treeDeptId
      };
      this.isShow = false;
    },
    //编辑跳转页面
    editOpen(row, index) {
      this.detailData = {
        id: row.id
      };
      this.isShow = false;
    },
    //删除触发
    rowDel(row, index, done) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        });
    },
    searchReset() {
      this.query = {};
      this.treeDeptId = "";
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    handleGrant() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.roleTreeObj = [];
      if (this.selectionList.length === 1) {
        this.roleTreeObj = this.selectionList[0].roleId.split(",");
      }
      getRoleTree().then(res => {
        this.roleGrantList = res.data.data;
        this.roleBox = true;
      });
    },
    handlePlatform() {
      this.platformBox = true;
    },
    handleImport() {
      this.excelBox = true;
    },
    handleTemplate() {
      window.open(
        `/api/blade-user/export-template?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    //新增编辑查看触发
    async beforeOpen(done, type) {
      if (["add"].includes(type)) {
        this.option.column.forEach(e => {
          if (e.prop == "goodsTypeId") {
            this.$set(this.option.column, 2, { ...e, value: this.treeDeptId });
          }
        });
      }
      if (["edit", "view"].includes(type)) {
        await getUser(this.form.id).then(res => {
          this.form = res.data.data;
          // this.form.goodsTypeId = [this.form.goodsTypeId.replace(/\"/g,"")]
          console.log(this.form.hasOwnProperty("goodsTypeId"));
          if (this.form.hasOwnProperty("goodsTypeId")) {
            this.form.goodsTypeId = this.form.goodsTypeId.split(",");
          }
        });
      }
      if (["add", "edit"].includes(type)) {
        this.initData(0);
      }
      this.initFlag = true;
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query),
        this.treeDeptId
      ).then(res => {
        const data = res.data.data;
        this.data = data.records;
        this.page.total = res.data.data.total;
        this.loading = false;
        this.selectionClear();
      });
    },
    platformRowUpdate(row, index, done, loading) {
      updatePlatform(row.id, row.userType, row.userExt).then(
        () => {
          this.platformOnLoad(this.platformPage);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    openReport() {
      this.switchDialog = !this.switchDialog;
    },
    onClose(val) {
      this.switchDialog = val;
    },
    platformBeforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getUserPlatform(this.platformForm.id).then(res => {
          this.platformForm = res.data.data;
        });
      }
      done();
    },
    platformSearchReset() {
      this.platformQuery = {};
      this.platformOnLoad(this.platformPage);
    },
    platformSearchChange(params, done) {
      this.platformQuery = params;
      this.platformPage.currentPage = 1;
      this.platformOnLoad(this.platformPage, params);
      done();
    },
    platformSelectionChange(list) {
      this.platformSelectionList = list;
    },
    platformSelectionClear() {
      this.platformSelectionList = [];
      this.$refs.platformCrud.toggleSelection();
    },
    platformCurrentChange(currentPage) {
      this.platformPage.currentPage = currentPage;
    },
    platformSizeChange(pageSize) {
      this.platformPage.pageSize = pageSize;
    },
    platformRefreshChange() {
      this.platformOnLoad(this.platformPage, this.platformQuery);
    },
    platformOnLoad(page, params = {}) {
      this.platformLoading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query),
        this.treeDeptId
      ).then(res => {
        const data = res.data.data;
        this.platformPage.total = data.total;
        this.platformData = data.records;
        this.platformLoading = false;
        this.selectionClear();
      });
    },
    goBack() {
      this.detailData = this.$options.data().detailData;
      this.isShow = true;
    }
  }
};
</script>

<style>
.el-scrollbar {
  height: 100%;
}
</style>
