<template>
  <div v-if="pageStatus == 0">配置加载中...</div>
  <div v-else-if="pageStatus == 1">此页面不对此账号开放</div>
  <div v-else-if="pageStatus == 2">
    没有此页内容的配置权限，请检查集团上的配置
  </div>
  <div v-else-if="pageStatus == 3">加载发生错误</div>
  <div v-else-if="pageStatus == 4" class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
    >
      <el-form-item style="float: right">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >添加加油员</el-button
        >
      </el-form-item>
    </el-form>
    <div
      class="mt-5"
      style="text-align: center"
      v-if="personnelList.length == 0"
    >
      请至少添加一名加油员，否则小程序无法进行支付~
    </div>
    <el-table :data="personnelList" v-else>
      <el-table-column
        label="油站加油员主键id"
        v-if="false"
        align="center"
        prop="personnelId"
      />
      <el-table-column label="加油员姓名" align="center" prop="personnelName" />
      <el-table-column label="负责枪号" align="center" prop="gunNo" />
      <el-table-column label="手机号" align="center" prop="personnelPhone" />
      <el-table-column
        label="加油站名称"
        align="center"
        prop="stationName"
        v-if="jiBie != 2"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="exportQr(scope.row)"
            v-if="personnelList.length != 1"
            >导出员工码</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            v-if="personnelList.length == 1"
            @click="exportQr(scope.row)"
            >导出油站码</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改油站加油员信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="personnelName">
          <el-input
            v-model="form.personnelName"
            placeholder="请输入加油员姓名"
          />
        </el-form-item>
        <el-form-item label="负责枪号" prop="checkedGunList">
          <template v-if="allGunList.length === 0">
            请先在油枪管理里配置油枪
          </template>
          <template v-else>
            <el-checkbox-group v-model="form.checkedGunList">
              <el-checkbox
                v-for="item in allGunList"
                :key="item.oilGunId"
                :label="item.oilGunNo"
                :value="item.oilGunNo"
              >
                {{ item.oilGunNo + "号枪/" + item.oilName }}
              </el-checkbox>
            </el-checkbox-group>
          </template>
        </el-form-item>
        <el-form-item label="手机号" prop="personnelPhone">
          <el-input
            v-model="form.personnelPhone"
            placeholder="请输入加油员手机号"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="
        personnelList.length == 0
          ? '添加加油员须知'
          : personnelList.length == 1
          ? '添加加油员确认'
          : '删除加油员确认'
      "
      :visible.sync="confirmDialog"
      width="500px"
      append-to-body
    >
      <div class="m-2 mt-0" v-if="personnelList.length == 0">
        <div style="text-align: center">关于加油员</div>
        <div style="color: red; font-size: 12px; text-indent: 2em" class="mt-3">
          1、请至少添加一名加油员，否则小程序无法进行支付。
        </div>
        <div style="color: red; font-size: 12px; text-indent: 2em" class="mt-2">
          2、当您只添加 【<b>一名加油员</b>】
          ：小程序采取开放模式（即用户<b>可以不通过扫员工码进入</b>），小程序会拉取该加油员所管理的油枪，用户产生的订单全部算在该加油员的名下。
        </div>
        <div
          style="color: red; font-size: 12px; text-indent: 2em"
          class="mt-2 mb-3"
        >
          3、当您添加了 【<b>多名加油员</b>】
          ：小程序采取限制模式（即<b>只能够通过扫员工码进入</b>），小程序会拉取对应员工码下的加油员所管理的油枪，用户扫员工码产生的订单算在对应加油员的名下。
        </div>
      </div>
      <div class="m-2" v-else-if="personnelList.length == 1">
        <div>你当前只有一名加油员，所有的订单都会计入该加油员名下。</div>
        <div class="mt-2">
          您正在添加第二名加油员，操作成功之后，<b>系统将发生以下变化：</b>
        </div>
        <div style="color: red; font-size: 12px; text-indent: 2em" class="mt-4">
          1、小程序端会限制用户进入的方式，用户只能通过<b>扫描加油员的员工码</b>来进入小程序进行支付。其他方式进入小程序，会强制调用相机启动扫一扫功能。
        </div>
        <div style="color: red; font-size: 12px; text-indent: 2em" class="mt-2">
          2、用户扫描员工码产生的订单，会自动计入到员工码对应的加油员身上。
        </div>
        <div style="color: red; font-size: 12px; text-indent: 2em" class="mt-2">
          3、如果您启用了标签，可能需要导出多个<b>加油员标签码</b>~
          当然，不想使用太多标签码，也可以组合搭配使用，详情可以到标签模块了解~
        </div>
        <div class="mt-4 text-secondary">
          如果您对上述内容有清晰的了解，继续想添加加油员，请点击确认按钮。
        </div>

        <div class="mt-2 text-secondary">
          如果您对上面的内容不够了解，请联系运营人员来辅助设置。
        </div>
      </div>
      <div class="m-2" v-else-if="personnelList.length == 2">
        <div>您目前有两名加油员，订单会根据员工码计入加油员名下。</div>
        <div>
          您正在删除一名加油员，操作成功之后，<b>系统将发生以下变化：</b>
        </div>
        <div style="color: red; font-size: 12px; text-indent: 2em" class="mt-4">
          1、小程序端会开放用户进入的方式，用户可以通过多种方式进入小程序进行支付。
        </div>
        <div style="color: red; font-size: 12px; text-indent: 2em" class="mt-2">
          2、用户支付产生的所有订单，会自动计入到仅剩下的加油员的名下。
        </div>
        <div class="mt-4 text-secondary">
          如果您对上述内容有清晰的了解，继续想删除加油员，请点击删除按钮。
        </div>

        <div class="mt-2 text-secondary">
          如果您对上面的内容不够了解，请联系运营人员来辅助设置。
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button
          :type="
            personnelList.length == 0 || personnelList.length == 1
              ? 'primary'
              : 'danger'
          "
          @click="confirmSubmit"
          >{{
            personnelList.length == 0
              ? "我知道了~"
              : personnelList.length == 1
              ? "我已经了解，继续添加加油员"
              : "我已经了解，确认删除该加油员"
          }}</el-button
        >
        <el-button @click="confirmCancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="exportQrDialog"
      width="600px"
      append-to-body
      title="导出标签"
    >
      <div>
        <qr :text="qrStr" @downloadImg="downloadImg" :name="personnelList.length==1 ? '油站码' : '员工码'">
          <div v-if="personnelList.length==1">油站码：{{this.$store.state.user.deptName}}-{{ this.currentExport.personnelName }}</div>
          <div v-else>员工码：{{this.$store.state.user.deptName}}-{{ this.currentExport.personnelName }}</div>
          <div class='mx-auto d-flex' style="width:500px;justify-content:center;align-items:center;">
            <span>负责枪号：</span> 
            <div class="d-inline-flex" style="max-width:350px;flex-wrap:wrap;justify-content:space-between;">
              <span v-for="ele in currentExport.checkedGunList" :key="ele" style="width: 85px;">
                {{ ele + '号枪-' + transferGunnumToOilname(ele) + " "}}
            </span>
            </div>
          </div>
        </qr>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPersonnel,
  getPersonnel,
  delPersonnel,
  addPersonnel,
  updatePersonnel,
  exportPersonnel,
} from "@/api/station/personnel";
import { stationinfo, listGun } from "@/api/station/gun";
import { getDept } from "@/api/system/dept";
import Base64 from "@/utils/base64";
import qr from "@/components/QrCode";

export default {
  name: "Station_Employee",
  data() {
    return {
      // 总条数
      total: 0,
      // 油站加油员信息表格数据
      personnelList: [],
      allGunList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        personnelName: null,
        gunNo: null,
        qrCode: null,
        personnelPhone: null,
      },
      // 查询参数
      queryInfo: {
        stationId: null,
      },
      query: {
        deptId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        personnelName: [
          { required: true, message: "请输入加油员姓名", trigger: "blur" },
        ],
        checkedGunList: [
          { required: true, message: "请选择油枪", trigger: "change" },
        ],
      },
      pageStatus: 0,
      confirmDialog: false,
      deletePersonnelId: undefined,
      exportQrDialog: false,
      qrStr: "",
      currentExport: {},
    };
  },
  components: {
    qr,
  },
  created() {
    const base = new Base64();
    const a = base.encode("12李哈哈");
    console.log("加密", a);
    console.log("解密", base.decode(a));
    this.init();
    this.setPageStatus();
  },
  methods: {
    downloadImg() {
      this.msgSuccess("导出成功~");
    },
    /** 查询油站加油员信息列表 */
    getList() {
      listPersonnel(this.queryParams).then((response) => {
        this.personnelList = response.rows;
        this.total = response.total;
      });
    },
    setPageStatus() {
      this.queryPageStatus([2]).then((res) => {
        this.pageStatus = res;
      });
    },
    confirmSubmit() {
      if (this.personnelList.length == 1 || this.personnelList.length == 0) {
        this.confirmDialog = false;
        this.open = true;
      } else if (this.personnelList.length == 2) {
        this.confirmDialog = false;
        delPersonnel(this.deletePersonnelId)
          .then((res) => {
            this.getList();
            this.msgSuccess("删除成功~");
          })
          .catch((res) => {
            this.msgError("删除失败~");
          });
      }
    },
    confirmCancel() {
      this.confirmDialog = false;
    },
    init() {
      //加载所有油枪
      this.getList();
      listGun({
        stationId: this.deptId,
      }).then((response) => {
        this.allGunList = response.rows;
        console.log('this.allGunList',this.allGunList);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    // /** 搜索按钮操作 */
    // handleQuery() {
    //   this.queryParams.pageNum = 1;
    //   this.getList();
    // },
    // /** 重置按钮操作 */
    // resetQuery() {
    //   this.resetForm("queryForm");
    //   this.handleQuery();
    // },
    /** 新增按钮操作 */
    handleAdd() {
      this.title = "添加油站加油员";
      //【**】
      this.form = {
        stationId: this.deptId,
        checkedGunList: [],
      };
      this.form.stationId = this.deptId;
      if (this.personnelList.length == 0 || this.personnelList.length == 1) {
        this.confirmDialog = true;
      } else {
        this.open = true;
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      let checkedGunList;
      if (Object.prototype.toString.call(row.gunNo) === "[object String]") {
        checkedGunList = [...new Set(row.gunNo.split(","))].filter((ele) => {
          return ele.toString().trim() !== "";
        });
      } else {
        checkedGunList = [];
      }
      this.form = { ...row, checkedGunList };
      this.open = true;
      this.title = "修改油站加油员";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let list = [];
          for (let i = 0; i < this.form.checkedGunList.length; i++) {
            for (let j = 0; j < this.allGunList.length; j++) {
              if (this.form.checkedGunList[i] == this.allGunList[j].oilGunNo) {
                list.push(this.allGunList[j].oilGunNo);
              }
            }
          }
          this.form.gunNo = list.toString();
          if (!!this.form.personnelId) {
            updatePersonnel(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPersonnel(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.deletePersonnelId = row.personnelId;
      if (this.personnelList.length == 2) {
        this.confirmDialog = true;
        return;
      }
      this.$confirm("是否确认删除油站加油员信息", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        console.log(123);
        delPersonnel(this.deletePersonnelId)
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功~");
          })
          .catch(() => {
            this.msgError("删除失败~");
          });
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有油站加油员信息数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportPersonnel(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    exportQr(row) {
      this.currentExport = JSON.parse(JSON.stringify(row));
      if (row.gunNo !== null) {
        this.currentExport.checkedGunList = [
          ...new Set(row.gunNo.split(",")),
        ].filter((ele) => {
          return ele.toString().trim() !== "";
        });
      } else {
        this.currentExport.checkedGunList = [];
      }
      const base = new Base64();
      const encodeStr = "e" + row.personnelId + "/";
      const encodedStr = base.encode(encodeStr);
      const trimEqualStr = encodedStr.replace(/={1,}$/g, "");
      this.qrStr = "https://goto.huijy.net/" + this.deptId + "/" + trimEqualStr;
      this.exportQrDialog = true;
    },
    transferGunnumToOilname(gunNo){
      const gun = this.allGunList.find((ele)=>{
        return ele.oilGunNo == gunNo;
      })
      return gun.oilName
    }
  },
};
</script>
