<template>
  <div v-if="pageStatus == 0">配置加载中...</div>
  <div v-else-if="pageStatus == 1">此页面只对站点用户开发</div>
  <div v-else-if="pageStatus == 4">
    <div
      style="
        width: 450px;
        margin: 0 auto;
        margin-top: 20px;
        margin-bottom: 60px;
        border: 1px solid red;
        box-sizing: border-box;
        padding: 20px;
      "
    >
      <div style="color: red; font-size: 12px">
        <span style="display: inline-block; width: 20px"> </span>
        1、标签用于对不同用户群体进行区别定价。
      </div>
      <div style="color: red; font-size: 12px">
        <span style="display: inline-block; width: 20px"> </span>
        2、标签的优先级高于营销方案。所以将用户加入标签后，此用户将优先执行标签的优惠规则，不会再执行营销方案。
      </div>
      <div style="color: red; font-size: 12px">
        <span style="display: inline-block; width: 20px"> </span>
        3、标签码用于给用户扫码使用，从而让用户享受对应的标签优惠，实现灵活处理，方便快捷。您还可以配置是否强制拉用户进入标签，实现用户长期留在此标签。
      </div>
    </div>

    <el-form
      :model="labelForm"
      ref="labelForm"
      label-width="90px"
      style="width: 400px; margin: 0 auto"
      label-position="left"
    >
      <el-form-item
        label="启用标签"
        prop="labelFlag"
        :rules="{
          required: true,
          message: '请选择是否开启标签',
          trigger: 'change',
        }"
      >
        <el-radio-group v-model="labelForm.labelFlag" :disabled="editable">
          <el-radio label="0">关闭</el-radio>
          <el-radio label="1">开启</el-radio>
        </el-radio-group>
      </el-form-item>
      <div
        v-if="
          labelForm.labelFlag == 1 && (labelForm.labelArr || []).length == 0
        "
      >
        <el-form-item label=" ">
          您没有添加标签，所以标签功能尚未生效
        </el-form-item>
      </div>
      <div v-if="labelForm.labelFlag == 1">
        <el-form-item
          v-for="(label, index) in labelForm.labelArr"
          :label="'标签' + (index + 1)"
          :key="index"
          :prop="'labelArr.' + index + '.labelName'"
          :rules="{
            required: true,
            message: '标签不能为空,不需要请删除此项',
            trigger: 'blur',
          }"
        >
          <el-input v-model="label.labelName" :disabled="editable"></el-input>
          <el-popconfirm
            title="此标签在用，删除后之前导出的支付码将失效，删除前请仔细检查，是否删除？"
            confirm-button-text="删除"
            @onConfirm="removeLabel(label)"
            v-if="!!label.id"
          >
            <el-button
              slot="reference"
              :disabled="editable"
              :loading="label.loading"
              class="mt-2"
              >删除</el-button
            >
          </el-popconfirm>
          <el-button
            @click="removeLabel(label)"
            :disabled="editable"
            :loading="label.loading"
            class="mt-2"
            v-else
            >删除</el-button
          >
          <el-button
            @click="exportPayCode(label)"
            v-show="editable"
            :loading="label.loading"
            class="mt-2 ml-3"
            >导出标签码</el-button
          >
        </el-form-item>
      </div>
      <el-form-item>
        <el-button
          @click="addLabel"
          :disabled="editable"
          v-show="labelForm.labelFlag == 1"
          >新增</el-button
        >
        <el-button type="danger" @click="editLabel">{{
          editable ? "修改标签" : "取消"
        }}</el-button>
        <el-button
          type="primary"
          @click="submitForm('labelForm')"
          :disabled="editable"
          v-show="!editable"
          >提交</el-button
        >
      </el-form-item>
    </el-form>

    <el-dialog
      :visible.sync="selectQrDialog"
      width="700px"
      append-to-body
      title="选择导出标签"
    >
      <div
        class="d-block mx-auto"
        style="width: 600px; text-align: center"
        id="qrDiv"
      >
        <h5>标签码设置</h5>
        用户扫码支付后，是否<b>强制将用户拉入此标签</b>？
        <el-switch
          v-model="exportLabelQr.isAddLabel"
          active-value="1"
          inactive-value="0"
          @change="handleStatusChange"
        ></el-switch
        ><br />
        当前设置：{{
          exportLabelQr.isAddLabel == "1"
            ? "支付后强拉至此标签，下次扫员工码和站点码都可以实现此标签优惠~"
            : "支付后不强拉到此标签，下次想再享受此标签优惠需要再次扫此标签码~"
        }}
        <hr />
        <div v-if="personnelList.length != 1">
          <h5>总标签码</h5>
          <div>
            用户可以先扫描<span style="color: red; font-weight: bold">
              总标签码</span
            >，再让用户扫描
            <span style="color: red; font-weight: bold">{{
              personnelList.length == 1 ? "站点码" : "员工码"
            }}</span>
            ，即可实现标签优惠。
          </div>
          <div>此码<b>适用所有的加油员</b>，不过需要<b>用户扫码两次</b>~</div>
          <div class="btn btn-success mt-3" @click="exportSumLabel">导出【总标签码】</div>
          <hr />
        </div>
        <div>
          <h5>员工标签码</h5>
          <div>
            用户可以一次性扫描<span style="color: red; font-weight: bold">
              员工标签码</span
            >，实现标签优惠。
          </div>
          <div>
            此码是<b>一个加油员一个标签码</b>，用户只需要<b>扫码一次</b>。
          </div>
          <div v-if="personnelList.length == 1">
            <h5 style="color: red">
              您的站点目前<b>仅有一个加油员</b>，请优先使用此码~
            </h5>
          </div>
          <div v-for="emp in personnelList" :key="emp.personnelId">
            <div class="btn btn-primary mt-3" @click="exportEmployeeLabel(emp)">
              导出{{ emp.personnelName }}的【员工标签码】
            </div>
          </div>
          <br />
        </div>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="exportQrDialog"
      width="600px"
      append-to-body
      title="导出标签"
    >
      <div>
        <qr :text="currentExport.text" @downloadImg="downloadImg" :name="currentExport.type==1 ? '员工标签码':'总标签码'">
          <div v-if="currentExport.type==1">员工标签码：{{this.$store.state.user.deptName}}-{{currentExport.name}}-{{ currentExport.labelName }}</div>
          <div v-if="currentExport.type==0">总标签码：{{this.$store.state.user.deptName}}-{{ currentExport.labelName }}</div>
        </qr>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  sysDeptDemoList,
  addlabel,
  selectLabel,
  updateLabelRule,
} from "@/api/label/label";
import qr from "@/components/QrCode";
import { listPersonnel } from "@/api/station/personnel";
import Base64 from "@/utils/base64";

export default {
  name: "Label_AddLabel",
  data() {
    return {
      labelForm: {
        labelFlag: "0",
        labelArr: [
          {
            id: "",
            labelName: "hah",
          },
        ],
        delArr: [],
      },
      editable: true,
      tempForm: undefined,
      pageStatus: 0,
      selectQrDialog: false,
      exportQrDialog: false,
      exportLabelQr: {},
      exportEmployeeQr: {},
      personnelList: [],
      currentExport:{
        name:'',
        type:1, // 0 总标签码 1 员工标签码
        text:'',
        labelName:'',
        labelId:'',
      },
      base:null
    };
  },
  created() {
    this.init();
  },
  components: {
    qr,
  },
  methods: {
    init() {
      this.setPageStatus();
      this.getList();
      this.getEmployeeList();
      this.base = Base64.getInstance();
    },
    getEmployeeList() {
      listPersonnel({
        pageNum: 1,
        pageSize: 1000,
      })
        .then((res) => {
          if (res.code == 200) {
            this.personnelList = res.rows;
          } else {
            throw new Error("");
          }
        })
        .catch((err) => {
          this.msgError("加载员工列表出错了~");
        });
    },
    setPageStatus() {
      this.queryPageStatus([2]).then((res) => {
        this.pageStatus = res;
      });
    },
    test() {},
    getList() {
      return sysDeptDemoList().then((res) => {
        if (res.code == 200) {
          this.labelForm = res.data;
          this.labelForm.delArr = [];
        } else {
          this.msgError("初始化数据失败");
        }
      });
    },
    submitForm(labelForm) {
      this.$refs[labelForm].validate((valid) => {
        if (valid) {
          addlabel(this.labelForm).then((res) => {
            if (res.code == 200) {
              this.getList().then((res) => {
                this.editable = true;
                this.msgSuccess("标签提交成功！");
              });
            } else {
              this.msgError("标签提交时出现错误，请刷新重试！");
            }
          });
        }
      });
    },
    resetForm(labelForm) {
      this.$refs[labelForm].resetFields();
    },
    removeLabel(item) {
      item.loading = true;
      this.labelForm = { ...this.labelForm };
      if (!item.id) {
        var index = this.labelForm.labelArr.indexOf(item);
        if (index !== -1) {
          this.labelForm.labelArr.splice(index, 1);
        }

        item.loading = false;
        this.labelForm = { ...this.labelForm };
        return;
      }
      selectLabel({
        labelId: item.id,
      }).then((res) => {
        if (res.code == 200) {
          if (res.data) {
            this.labelForm.delArr.push(item.id);
            var index = this.labelForm.labelArr.indexOf(item);
            if (index !== -1) {
              this.labelForm.labelArr.splice(index, 1);
            }
            item.loading = false;
            this.labelForm = { ...this.labelForm };
          } else {
            this.msgError("请先清空标签下的成员之后，再来删除标签操作");
            item.loading = false;
            this.labelForm = { ...this.labelForm };
          }
        } else {
          this.msgError("查询标签状态失败，请重试");
          item.loading = false;
          this.labelForm = { ...this.labelForm };
        }
      });
    },
    addLabel() {
      this.labelForm.labelArr.push({
        labelName: "",
        key: Date.now(),
      });
    },
    editLabel() {
      if (!this.editable) {
        if (this.tempForm !== undefined) {
          this.labelForm = JSON.parse(this.tempForm);
          this.labelForm.delArr = [];
        }
      } else {
        this.tempForm = JSON.stringify({ ...this.labelForm });
      }
      this.editable = !this.editable;
    },
    exportPayCode(label) {
      this.exportLabelQr = label;
      this.currentExport.labelName = label.labelName;
      this.currentExport.labelId = label.id;
      this.selectQrDialog = true;
    },
    downloadImg() {
      html2canvas(document.getElementById("qrDiv"), { allowTaint: true }).then(
        (canvas) => {
          const a = document.createElement("a");
          const event = new MouseEvent("click");
          a.download = "标签支付码";
          a.href = canvas.toDataURL();
          a.dispatchEvent(event);
        }
      );

      // // const iconUrl = this.$refs['Qrcode'].$el.src
      // const a = document.createElement('a')
      // const event = new MouseEvent('click')
      // console.log()
      // a.download = '标签支付码'
      // a.href = iconUrl
      // a.dispatchEvent(event)
    },
    handleStatusChange(e) {
      const old = this.exportLabelQr.isAddLabel;
      updateLabelRule({
        id: this.exportLabelQr.id,
        isAddLabel: e,
      })
        .then((res) => {
          if (res.code == 200) {
            this.msgSuccess("恭喜你，修改成功了~");
          } else {
            throw new Error("");
          }
        })
        .catch((err) => {
          this.exportLabelQr.isAddLabel = old;
          this.msgError("抱歉，修改失败了，请刷新网页重试~");
        });
    },
    downloadImg(){
      this.msgSuccess("亲，导出成功了~")
    },
    exportEmployeeLabel(emp){
      this.currentExport.name = emp.personnelName;
      this.currentExport.type = 1;

      const encodeStr = "e" + emp.personnelId + "/l" + this.currentExport.labelId + "/";
      const encodedStr = this.base.encode(encodeStr);
      const trimEqualStr = encodedStr.replace(/={1,}$/g, "");
      this.currentExport.text = "https://goto.huijy.net/" + this.deptId + "/" + trimEqualStr;
      this.exportQrDialog = true;
    },
    exportSumLabel(){
      const encodeStr =  "l" + this.currentExport.labelId + "/";
      const encodedStr = this.base.encode(encodeStr);
      const trimEqualStr = encodedStr.replace(/={1,}$/g, "");
      this.currentExport.text = "https://goto.huijy.net/" + this.deptId + "/" + trimEqualStr;
      this.currentExport.type = 0
      this.exportQrDialog = true;
    }
  },
};
</script>
<style scoped lang="scss">
</style>