<template>
  <div class="page-container">
    <div class="filter-container">
      <SelectJoin
        ref="selectJoinRef"
        :columns="selectJoinColumns"
        @change="onSelectJoinChange"
      />
      <div class="filter-item">
        <div class="filter-item-label">商品名称</div>
        <div class="filter-item-content">
          <el-input
            v-model="listQuery.productName"
            clearable
            placeholder="商品名称"
            @keyup.enter.native="handleFilter"
            class="filter-item-control"
          />
        </div>
      </div>
      <div class="filter-item">
        <div class="filter-item-label">客户经理</div>
        <div class="filter-item-content">
          <el-input
            v-model="listQuery.customerManagerName"
            clearable
            placeholder="客户经理"
            @keyup.enter.native="handleFilter"
            class="filter-item-control"
          />
        </div>
      </div>
      <div class="filter-item">
        <div class="filter-item-label">状态</div>
        <div class="filter-item-content">
          <el-select v-model="listQuery.status" clearable placeholder="状态">
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
      </div>
      <div class="filter-item">
        <el-button
          size="mini"
          type="warning"
          style="background: rgb(255, 148, 0);"
          @click="handleFilter"
        >
          查询
        </el-button>
        <el-button size="mini" type="primary" plain @click="handleFilterReset"
          >重置
        </el-button>
      </div>
    </div>
    <div class="head-line" />
    <div class="action-container">
      <el-button
        icon="el-icon-plus"
        size="mini"
        type="primary"
        @click="handleCreate"
      >
        新增
      </el-button>

      <!-- <el-button icon="el-icon-plus" size="mini" type="primary" @click="onRewardDialogOpen">
        拓新激励
      </el-button> -->
      <el-button
        icon="el-icon-document"
        size="mini"
        type="primary"
        plain
        @click="importExcel"
      >
        导入
      </el-button>
      <el-button
        icon="el-icon-download"
        type="primary"
        plain
        @click="downloadTemplate"
      >
        下载模版
      </el-button>
      <el-button icon="el-icon-download" type="primary" @click="exportExcel">
        导出到excel
      </el-button>
      <el-button icon="el-icon-download" type="primary" @click="exportExcel2">
        导出房间企业信息
      </el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" border style="width: 100%;">
      <el-table-column type="index" align="center" label="序号" width="50" />
      <el-table-column prop="roomInfo" align="center" label="房间号" />
      <el-table-column prop="virtName" align="center" label="企业名称" />
      <el-table-column prop="residentNum" align="center" label="常驻人数" />
      <el-table-column
        prop="merchantQuantityInfo"
        align="center"
        label="商品名称"
      />
      <el-table-column prop="status" align="center" label="状态">
        <template slot-scope="{ row }">
          {{ row.status | enumFormatter(statusList) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="customerManagerName"
        align="center"
        label="客户经理"
      />
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="200"
        label="操作"
      >
        <template slot-scope="{ row, $index }">
          <div class="operate-container">
            <span class="operate-btn" @click="handleUpdate(row, $index)">
              修改
            </span>
            <span
              class="operate-btn"
              @click="onJiaoshuimaDialogOpen(row, $index)"
            >
              叫水码
            </span>
            <!-- <span class="operate-btn" @click="handleDelete(row, $index)">
              删除
            </span> -->
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 拓新激励 -->
    <el-dialog
      width="400px"
      title="拓新激励"
      :visible="rewardDialogVisible"
      :before-close="onRewardDialogClose"
    >
      <el-form ref="postForm" :model="rewardPostForm" label-width="100px">
        <el-form-item label="开拓奖励" prop="textarea">
          <div>
            <number-input
              v-model="rewardPostForm.price"
              :value="rewardPostForm.price"
              placeholder="请输入金额"
            />
            <span>元/企业</span>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="onRewardSubmit"
          :loading="rewardSubmitLoading"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <!-- 叫水码 -->
    <el-dialog
      width="400px"
      title="叫水码"
      :visible="jiaoshuimaDialogVisible"
      :before-close="onJiaoshuimaDialogClose"
    >
      <div style="margin: 0 auto 20px;text-align:center;">
        {{ jiaoshuimaPostForm.virtName }}
      </div>
      <div
        id="qrcode"
        style="width:250px;height:250px;overflow: hidden;margin: 0 auto;"
        ref="qrcode"
      ></div>
      <div class="a">
        {{ jiaoshuimaPostForm.link }}
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          v-clipboard:copy="jiaoshuimaPostForm.link"
          v-clipboard:success="onJiaoshuimaDialogCopy"
          >复制链接</el-button
        >
        <el-button type="primary" @click="onJiaoshuimaDialogDownload"
          >下载二维码</el-button
        >
      </div>
    </el-dialog>
    <import-excel
      ref="importExcel"
      :visible.sync="importExcelVisible"
      @submit="onImportExcelSubmit"
    ></import-excel>
  </div>
</template>
<script>
import API_FLASHDELIVER_JIAOSHUIMA from "@/api/flashdeliver/jiaoshuima";
import {
  companyGetselectlist,
  organizationGetselectlist,
  organisationVirtualarchitectureList
} from "@/api/flashdeliver/jiaoshuima";
import Pagination from "@/components/Pagination";
var pageFlag = false;
// 状态列表
export const statusList = [
  { label: "待转化", value: 2 },
  { label: "未启用", value: 1 },
  { label: "客户", value: 3 }
];
import NumberInput from "@/components/NumberInput";
import ImportExcel from "./components/ImportExcel";
import FileSaver from "file-saver";
import QRCode from "qrcodejs2";
import SelectJoin from "./components/SelectJoin";

export default {
  name: "jiaoshuima",
  components: {
    Pagination,
    NumberInput,
    SelectJoin,
    ImportExcel
  },
  data() {
    return {
      selectJoinColumns: this.getSelectJoinColumn(),
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 10,
        productName: "",
        status: null,
        customerManagerName: "",
        virtId: "",
        virtName: "",
        projectId: "",
        operationsCenterId: ""
      },
      statusList,
      operationsCenterList: [], // 运营中心列表
      projectList: [], // 项目列表
      virtList: [], // 企业列表
      loading: false,
      // 导入excel
      importExcelVisible: false,
      importExcelLoading: false,
      // 拓新激励弹窗
      rewardDialogVisible: false,
      rewardSubmitLoading: false,
      rewardPostForm: {
        price: null
      },
      // 叫水码弹窗
      jiaoshuimaDialogVisible: false,
      jiaoshuimaPostForm: {
        virtName: "",
        link: ""
        // link: "http://wx.palmnest.com/super_cloud/api/wechat/q/r?p=3&p1=615&p2=185&p3=&_s=0"
      }
    };
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo;
    }
  },
  created() {
    console.log("created");
    pageFlag = true;
    this.getPage();
  },
  activated() {
    console.log("activated");
    if (pageFlag) {
      pageFlag = false;
      return;
    }

    this.getPage();
  },
  methods: {
    getSelectJoinColumn() {
      return [
        {
          field: "operationsCenterId",
          value: "",
          defaultValue: "",
          label: "运营中心",
          fileNames: { label: "label", value: "value", options: "items" },
          componentProps: {
            clearable: true,
            filterable: true,
            placeholder: "请选择运营中心"
          },
          options: [],
          api: () => {
            return companyGetselectlist();
          },
          afterFetch: data => {
            if (data && data.length) {
              const operationsCenterId = data[0].value;
              this.listQuery.operationsCenterId = operationsCenterId;
              this.$refs.selectJoinRef.setColumnValue(0, operationsCenterId)
            }
            return data;
          }
        },
        {
          field: "projectId",
          value: "",
          defaultValue: "",
          label: "项目",
          componentProps: {
            clearable: true,
            filterable: true,
            placeholder: "请选择项目"
          },
          options: [],
          api: () => {
            const params = {
              pageNo: 1,
              pageSize: 999
            };

            this.listQuery.operationsCenterId &&
              (params[
                "conditions[companyId]"
              ] = this.listQuery.operationsCenterId);

            return organizationGetselectlist(params);
          }
        },
        {
          field: "virtId",
          value: "",
          defaultValue: "",
          label: "企业",
          options: [],
          api: async () => {
            const params = {
              pageNo: 1,
              pageSize: 999
            };

            this.listQuery.projectId &&
              (params["conditions[orgId]"] = this.listQuery.projectId);

            return await organisationVirtualarchitectureList(params);
          }
        }
      ];
    },
    onSelectJoinChange({ selectedValues }) {
      console.log(`onSelectJoinChange`, selectedValues);
      this.selectJoinColumns.forEach(column => {
        this.listQuery[column.field] = column.value;
      });

      //  if (res.data && res.data.length) {
      //   const operationsCenterId = res.data[0].value;
      //   this.listQuery.operationsCenterId = operationsCenterId;
      //   this.getProjectList();
      // }
    },
    enumFormatter(
      val,
      arr,
      key = "value",
      label = "label",
      def = EMPTY_PLACEHOLDER
    ) {
      const target = arr.find(v => v[key] === val);
      if (label === "obj") {
        return target;
      } else {
        return target ? target[label] : def;
      }
    },
    async getPage() {
      // if (this.userInfo.userTypeModel == "project") {
      //   this.listQuery.operationsCenterId = this.userInfo.companyId;
      //   this.listQuery.projectId = this.userInfo.orgId;
      //   this.getVirtList();
      // } else if (this.userInfo.userTypeModel == "operationsCenter") {
      //   this.listQuery.operationsCenterId = this.userInfo.companyId;
      //   await this.getProjectList();
      // } else {
      //   await this.getOperationsCenterList();
      // }

      this.$nextTick(async () => {
        await this.$refs.selectJoinRef.loadData();
        this.getList();
      });
    },
    getListQueryModel() {
      const params = {
        pageNo: this.listQuery.page,
        pageSize: this.listQuery.limit,
        conditions: {}
      };

      this.listQuery.operationsCenterId &&
        (params.conditions.operationsCenterId = this.listQuery.operationsCenterId);
      this.listQuery.projectId &&
        (params.conditions.orgId = this.listQuery.projectId);
      this.listQuery.virtId &&
        (params.conditions.virtId = this.listQuery.virtId);
      this.listQuery.virtId &&
        (params.conditions.virtName = this.listQuery.virtName);
      this.listQuery.productName &&
        (params.conditions.productName = this.listQuery.productName);
      this.listQuery.customerManagerName &&
        (params.conditions.customerManagerName = this.listQuery.customerManagerName);
      this.statusList.some(v => v.value === this.listQuery.status) &&
        (params.conditions.status = this.listQuery.status);

      return params;
    },
    getList() {
      this.listLoading = true;

      API_FLASHDELIVER_JIAOSHUIMA.page(this.getListQueryModel())
        .then(res => {
          this.list = res.data;
          this.total = res.count;
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    // 查询
    handleFilter() {
      this.getList();
    },
    // 重置
    handleFilterReset() {
      this.listQuery.virtId = "";
      this.listQuery.virtName = "";
      this.listQuery.customerManagerName = "";
      this.listQuery.productName = "";
      this.listQuery.status = null;
    },
    handleCreate() {
      const query = {};
      this.handleAddOrUpdate(query);
    },
    handleUpdate(row, index) {
      const { id, virtId, roomMarkId } = row;
      const query = { id, virtId, roomMarkId };
      this.handleAddOrUpdate(query);
    },
    handleAddOrUpdate(query) {
      this.$router.push({
        path: "/flashdeliver/jiaoshuima/add-or-update",
        query
      });
    },
    handleDelete(row, index) {
      this.$confirm("确认删除" + row.name + "?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          API_FLASHDELIVER_JIAOSHUIMA.del(row.id).then(res => {
            this.$message({
              type: "success",
              message: "删除成功!",
              duration: 1500
            });
            this.list.splice(index, 1);
            this.total -= 1;
          });
        })
        .catch(() => {});
    },
    onRewardDialogOpen() {
      this.rewardDialogVisible = true;
    },
    onRewardDialogClose() {
      this.rewardDialogVisible = false;
    },
    onJiaoshuimaDialogOpen(row, _index) {
      this.jiaoshuimaPostForm = {
        virtId: row.virtId,
        virtName: row.virtName,
        link: row.waterCodeUrl
      };
      if (row.waterCodeUrl) {
        this.jiaoshuimaDialogVisible = true;
        this.$nextTick(() => {
          this.$refs.qrcode.innerHTML = ""; // 避免重复生成Dom
          let qrCode = new QRCode(this.$refs.qrcode, {
            width: 500,
            height: 500,
            text: this.jiaoshuimaPostForm.link
          });
        });
      } else {
        this.$message.error("叫水码地址为空!");
      }
    },
    onJiaoshuimaDialogClose() {
      this.jiaoshuimaDialogVisible = false;
    },
    onJiaoshuimaDialogCopy() {
      this.$message({
        type: "success",
        message: "成功复制",
        duration: 2000
      });
    },
    onJiaoshuimaDialogDownload() {
      // const base64 = this.$refs.qrcode.children[1].src;
      const canvas = this.$refs.qrcode.children[0];
      canvas.toBlob(blob => {
        FileSaver.saveAs(blob, "waterCodeUrl.png");
      });
    },
    onRewardSubmit() {
      this.rewardSubmitLoading = true;
    },
    onImportExcelSubmit() {
      this.importExcelVisible = false;
      this.getList();
    },
    // 导入
    importExcel() {
      if (this.userInfo.userTypeModel == "operationsCenter") {
        this.$refs.importExcel.postForm.operationsCenterId = this.userInfo.companyId;
        this.$refs.importExcel.init();
      } else if (this.userInfo.userTypeModel == "project") {
        this.$refs.importExcel.postForm.operationsCenterId = this.userInfo.companyId;
        this.$refs.importExcel.postForm.projectId = this.userInfo.orgId;
      } else {
        this.$refs.importExcel.init();
      }

      this.importExcelVisible = true;

      this.$refs.importExcel.userInfo = this.userInfo;
    },

    // 导出
    exportExcel() {
      if (!this.list.length) {
        this.$message.error("还没有数据!");
        return;
      }

      this.$confirm("此操作将导出报表数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          API_FLASHDELIVER_JIAOSHUIMA.exportExcel(
            this.getListQueryModel()
          ).then(res => {
            const rootUrl = process.env.BASE_API.substring(
              0,
              process.env.BASE_API.length - 3
            );
            const linkUrl = rootUrl + "template/WaterCode.xls";
            console.log("导出叫水码excel地址", linkUrl);
            location.href = linkUrl;
          });
        })
        .catch(() => {});
    },
    exportExcel2() {
      if (!this.list.length) {
        this.$message.error("还没有数据!");
        return;
      }

      if (!this.listQuery.projectId) {
        this.$message.error("请选择项目!");
        return;
      }

      this.$confirm("此操作将导出报表数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          API_FLASHDELIVER_JIAOSHUIMA.exportRoomInfo(
            this.getListQueryModel()
          ).then(res => {
            const rootUrl = process.env.BASE_API.substring(
              0,
              process.env.BASE_API.length - 3
            );
            const link = rootUrl + "template/RoomVirtName.xls";
            console.log("导出项目下房间和企业信息excel地址", link);
            location.href = link;
          });
        })
        .catch(() => {});
    },
    downloadTemplate() {
      let rootUrl = process.env.BASE_API.substring(
        0,
        process.env.BASE_API.length - 3
      );
      const link = rootUrl + "template/WaterCodeTemplate.xls";
      console.log("下载叫水码模版", link);
      location.href = link;
    },
    onOperationsCenterChange() {
      this.listQuery.projectId = "";
      this.handleFilterReset();
      this.getProjectList();
    },
    onProjectChange() {
      this.handleFilterReset();
      this.getVirtList();
    },
    onVirtChange() {
      this.listQuery.virtName = this.virtList.find(
        v => v.value === this.listQuery.virtId
      ).label;
    },
    async getVirtList() {
      const params = {
        pageNo: 1,
        pageSize: 999
      };

      this.listQuery.projectId &&
        (params["conditions[orgId]"] = this.listQuery.projectId);

      const res = await organisationVirtualarchitectureList(params);
      this.virtList = res.data || [];
      if (res.data && res.data.length === 1) {
        this.listQuery.virtId = res.data[0].value;
        this.listQuery.virtName = res.data[0].label;
      }
    },
    async getProjectList() {
      const params = {
        pageNo: 1,
        pageSize: 999
      };

      this.listQuery.operationsCenterId &&
        (params["conditions[companyId]"] = this.listQuery.operationsCenterId);

      const res = await organizationGetselectlist(params);
      this.projectList = res.data;
      if (res.data && res.data.length === 1) {
        this.listQuery.projectId = res.data[0].value;
        this.getVirtList();
      }
    },
    async getOperationsCenterList() {
      const res = await companyGetselectlist();
      this.operationsCenterList = res.data;
      if (res.data && res.data.length) {
        const operationsCenterId = res.data[0].value;
        this.listQuery.operationsCenterId = operationsCenterId;
        this.getProjectList();
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.filter-container {
  display: flex;
  flex-wrap: wrap;
  padding-bottom: 0;

  .filter-item {
    display: flex;
    align-items: center;
    margin-right: 10px;
    margin-bottom: 18px;

    &-label {
      box-sizing: border-box;
      font-size: 14px;
      color: #606266;
      font-weight: bold;
      padding: 0 12px 0 0;
    }
  }
}

.action-container {
  margin-bottom: 20px;
}

.operate-container {
  text-align: center;
}

.operate-btn {
  margin: 0 4px;
  cursor: pointer;
  color: #409eff;
}
</style>
