<template>
  <div class="a4-printer">
    <div class="model">
      <div class="setting-model">
        <div class="list">
          <div class="item">
            <div class="left">
              <div class="left-top">
                <div class="name">选择打印模板</div>
              </div>
              <div class="left-bot">根据您的制作和配送的场景选择适合的模板</div>
              <div class="module-list">
                <div @click="openModule(index)" class="module" v-for="(module,index) in moduleList" :key='index'>
                  <div class="img-wrap">
                    <img class="img" src="../../../../static/image/print-module.png" alt="">
                  </div>
                  <div class="module-right">
                    <div class="module-name">{{module.name}}</div>
                    <div class="module-tips">{{module.tips}}</div>
                  </div>
                  <div v-if="picturePrintModule === index+1" class="module-status">使用中</div>
                </div>
              </div>
            </div>
          </div>
          <div class="item" v-for="v in list" :key="v.field">
            <div class="left">
              <div class="left-top">
                <div class="name">{{v.name}}</div>
              </div>
              <div class="left-bot">{{v.tips}}</div>
            </div>
            <div class="right">
              <el-switch @change="change(v)" v-model="v.value" :active-value="1" :inactive-value="0" active-color="#FC7200" inactive-color="#999" />
            </div>
          </div>
          <div class="item">
            <div class="left">
              <div class="left-top">
                <div class="name">设置店铺联系号码</div>
              </div>
              <div class="left-bot">设置的店铺电话会打印在A4纸张上</div>
            </div>
            <div class="right" @click="openSettingPhone">
              <div class="right-name">{{picturePrintMobileType === 1 ? '统一设置' : '各店铺电话'}}</div>
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
          <div class="item">
            <div class="left">
              <div class="left-top">
                <div class="name">使用云盒打印</div>
              </div>
              <div class="printer-list">
                <div class="printer-item" v-for="(v,i) in printerList" :key="i">
                  <img class="img" src="../../../../static/image/printer-online-1.png" alt="">
                  <div class="name">{{v.name}}</div>
                  <div class="shop-name">{{v.shopName}}</div>
                  <div class="btns">
                    <img @click.stop="addPrinter(v)" src="../../../../static/image/edit-icon.png" alt="">
                    <img @click.stop="deletePrinter(v)" src="../../../../static/image/delete-icon.png" alt="">
                  </div>
                </div>
                <div v-if="!this.printerList.length" class="printer-item" @click.stop="addPrinter('')">
                  <img class="img" src="../../../../static/image/icon-add.png" alt="">
                  <div class="name">添加打印云盒</div>
                  <div class="shop-name"> </div>
                </div>
              </div>
            </div>
          </div>
          <div class="item" v-for="(v,i) in list1" :key=i>
            <div class="left">
              <div class="left-top">
                <div class="name">{{v.name}}</div>
              </div>
              <div class="left-bot">{{v.tips}}</div>
            </div>
            <div class="right">
              <el-switch @change="change(v)" v-model="v.value" :active-value="1" :inactive-value="0" active-color="#FC7200" inactive-color="#999" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 设置联系电话 -->
    <el-dialog title="电话设置" :visible.sync="showSettingPhone" width="500px" @close="getConfig">
      <el-select size="small" v-model="picturePrintMobileType" placeholder="请选择">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-input class="unify-phone" size="small" v-if="picturePrintMobileType===1" v-model="picturePrintMobile" placeholder="请输入统一的电话号码"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="showSettingPhone = false">取 消</el-button>
        <el-button size="small" type="primary" @click="confirmSettingPhone">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增、编辑云盒 -->
    <el-dialog title="云盒管理" :visible.sync="dialogVisible" @close="resetData" width="600px">
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="云盒名称">
          <el-input v-model="form.name" clearable placeholder="请自定义云盒名称"></el-input>
        </el-form-item>
        <el-form-item label="云盒序列号">
          <el-input v-model="form.deviceSn" clearable placeholder="请填写云盒序列号"></el-input>
        </el-form-item>
        <el-form-item label="云盒秘钥">
          <el-input v-model="form.deviceSecret" clearable placeholder="请填写云盒秘钥"></el-input>
        </el-form-item>
        <el-form-item label="关联门店">
          <el-select style="width:300px;" clearable v-model="form.shopIdList" multiple @change="changePrinterShop" max-width="300px">
            <el-option v-for="item in shopList" :key="item.id" :value="item.id" :label="item.name">
              <div>{{ item.name }}</div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择打印机">
          <el-select style="width:300px;" v-model="form.deviceName" placeholder="请选择打印机">
            <el-option v-for="item in cloudList" :key="item.id" :value="`${ item.driverName }(USB${item.port})`">
              <div>{{ item.driverName }}(USB{{item.port}})</div>
            </el-option>
          </el-select>
          <el-button type="success" @click="getCloudPrinterInfo">获取打印机信息</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="cloudPrinterManager">确 定</el-button>
      </span>
    </el-dialog>
    <!-- A4打印模板 -->
    <el-dialog :title="showTitle" :visible.sync="showModule" width="850px" top="5vh">
      <div style="height: 70vh">
        <iframe :src="moduleSrc" width="800px" height="100%" frameborder="0"></iframe>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showModule = false">取 消</el-button>
        <el-button type="primary" @click="saveModule">使 用</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getNewShopList,
  deviceAdd,
  shopDeviceList,
  deviceDelete,
  getCloudDevice,
} from "../../../api/shop";
import { getConfig, updateConfig } from "../../../api/setting.js";
import { mapState, mapMutations, mapGetters, mapActions } from "vuex";

export default {
  name: "a4Printer",
  data() {
    return {
      moduleList: [
        {
          name: "默认模板",
          tips: "配送单，不包含回执",
        },
        {
          name: "配送模板",
          tips: "配货单，包含预定人信息",
        },
        {
          name: "签收模板",
          tips: "配货签收",
        },
      ],
      picturePrintModule: 1,
      picturePrintMobile: "",
      list: [
        {
          name: "开启A4带图打印",
          value: 1,
          field: "openPicturePrint",
          tips: "开启A4带图打印需要打印机连接电脑，添加云盒可实现自动打印",
        },
      ],
      list1: [
        {
          name: "开启自动打印",
          value: 1,
          field: "openAutoPicturePrint",
          tips: "云盒添加后才可实现来单自动打印",
        },
      ],
      showSettingPhone: false,
      picturePrintMobileType: 2,
      options: [
        {
          value: 2,
          label: "各店铺联系电话",
        },
        {
          value: 1,
          label: "统一设置",
        },
      ],
      printerList: [],
      dialogVisible: false,
      shopList: [],
      form: {
        name: "",
        deviceSn: "",
        deviceSecret: "",
        shopIdList: [],
        deviceName: "",
        deviceType: 28,
        shopId: 0,
        lkyPrintType: 1,
      },
      showModule: false,
      moduleSrc: "",
      origin: "",
      cloudList: [],
      openModuleIndex: 0,
      showTitle: "选择默认模板",
      memberType: 2,
    };
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    let userInfo = JSON.parse(localStorage.getItem("userInfo"));
    this.memberType = userInfo.memberType;
    if (this.memberType === 3) {
      this.options = [
        {
          value: 2,
          label: "各店铺联系电话",
        },
      ];
    }
    this.origin = window.location.origin;
    this.getNewShopList();
    this.getCloudPrinterList();
    this.getConfig();
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  // 方法集合
  methods: {
    ...mapMutations(["SET_USERINFO"]),
    getCloudPrinterInfo() {
      if (!this.form.deviceSn) {
        return this.$message.warning(`请输入云盒序列号！`);
      }
      if (!this.form.deviceSecret) {
        return this.$message.warning(`请输入云盒秘钥！`);
      }
      let params = {
        deviceId: this.form.deviceSn,
        deviceKey: this.form.deviceSecret,
        printerType: 1,
      };
      getCloudDevice(params).then((res) => {
        console.log("云盒信息", res);
        if (!res.code) {
          this.cloudList = res.data;
          let cloud = this.cloudList[0];
          if (!cloud) return;
          this.form.deviceName = `${cloud.driverName}(USB${cloud.port})`;
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
    changePrinterShop(e) {
      if (e.at(-1)) {
        this.form.shopIdList = e.filter((v) => {
          return v;
        });
      } else {
        if (this.memberType === 2) {
          this.form.shopIdList = [0];
        } else {
          this.form.shopIdList = [];
        }
      }
    },
    openModule(index) {
      this.showModule = true;
      this.openModuleIndex = index + 1;
      switch (this.openModuleIndex) {
        case 1:
          this.showTitle = `选择默认模板`;
          break;
        case 2:
          this.showTitle = `选择配送模板`;
          break;
        case 3:
          this.showTitle = `选择签收模板`;
          break;

        default:
          break;
      }
      this.moduleSrc = `order-print-module/module${index}.html`;
    },
    saveModule() {
      this.picturePrintModule = this.openModuleIndex;
      this.updateConfig({ picturePrintModule: this.picturePrintModule });
    },
    openSettingPhone() {
      this.showSettingPhone = true;
    },
    confirmSettingPhone() {
      if (
        this.picturePrintMobileType === 1 &&
        !this.$tool.mobile(this.picturePrintMobile)
      ) {
        return this.$message.error("请输入正确的电话号码！");
      }
      this.updateConfig({
        picturePrintMobileType: this.picturePrintMobileType,
        picturePrintMobile: this.picturePrintMobile,
      });
    },
    deletePrinter(v) {
      this.$confirm("此操作将删除打印云盒, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          deviceDelete({ id: v.id }).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功！",
              });
              this.getCloudPrinterList();
            } else {
              this.$message({
                type: "error",
                message: res.msg,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    getNewShopList() {
      getNewShopList().then((res) => {
        if (res.code === 200) {
          if (this.memberType === 2) {
            res.data.unshift({ id: 0, name: "全部门店" });
          }
          this.shopList = res.data;
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
    addPrinter(v) {
      this.dialogVisible = true;
      if (v) this.form = this.$tool.deepClone(v);
      if (this.form.id) return;
      this.form.name = `贺卡打印云盒${new Date().getTime()}`;
      this.cloudList = [];
    },
    cloudPrinterManager() {
      if (!this.form.name) {
        return this.$message.warning(`请输入云盒名称！`);
      }
      if (!this.form.deviceSn) {
        return this.$message.warning(`请输入云盒序列号！`);
      }
      if (!this.form.deviceSecret) {
        return this.$message.warning(`请输入云盒秘钥！`);
      }
      let form = this.$tool.deepClone(this.form);
      form.shopIds = form.shopIdList.join();
      deviceAdd(form).then((res) => {
        console.log("添加云盒信息", res);
        if (res.code === 200) {
          this.$message.success(`成功添加云盒！`);
          this.dialogVisible = false;
          this.getCloudPrinterList();
          this.resetData();
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
    resetData() {
      this.form = {
        name: "",
        deviceSn: "",
        deviceSecret: "",
        shopIdList: [],
        deviceName: "",
        deviceType: 28,
        shopId: 0,
      };
    },
    getConfig() {
      getConfig().then((res) => {
        if (res.code === 200) {
          this.SET_USERINFO(res.data);
          this.list = this.list.map((v) => {
            v.value = res.data[v.field];
            return v;
          });
          this.list1 = this.list1.map((v) => {
            v.value = res.data[v.field];
            return v;
          });
          this.picturePrintMobileType = res.data.picturePrintMobileType;
          this.picturePrintModule = res.data.picturePrintModule;
          this.picturePrintMobile = res.data.picturePrintMobile;
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
    change(e) {
      let data = { [e.field]: e.value };
      this.updateConfig(data);
    },
    updateConfig(data) {
      updateConfig(data).then((res) => {
        if (res.code !== 200) {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
        this.showModule = false;
        this.showSettingPhone = false;
        this.getConfig();
      });
    },
    getCloudPrinterList() {
      shopDeviceList({ deviceType: 28, lkyPrintType: 1 }).then((res) => {
        if (res.code === 200) {
          this.printerList = res.data;
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped  type="text/css">
.model {
  .title {
    position: relative;
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: bold;
    line-height: 22px;
    color: #333333;
    padding-left: 10px;
    margin-top: 24px;
  }
  .title::before {
    width: 3px;
    height: 16px;
    background: rgba(252, 114, 0, 0.39);
    border-radius: 2px;
    content: "";
    position: absolute;
    top: 2px;
    left: 0;
  }
  /deep/ .el-button--default:hover {
    background-color: rgba(252, 114, 0, 0.2);
    border-color: rgba(252, 114, 0, 0.2);
    color: #fc7200;
  }
  /deep/ .el-button--primary {
    background-color: #fc7200;
    border-color: #fc7200;
  }

  .setting-model {
    .title {
      position: relative;
      font-size: 16px;
      font-weight: bold;
      line-height: 22px;
      color: #333333;
      padding-left: 10px;
      margin-top: 24px;
      .tips {
        font-size: 14px;
        font-weight: 400;
        line-height: 22px;
        color: #999999;
      }
    }
    .title::before {
      width: 3px;
      height: 16px;
      background: #fc7200;
      border-radius: 2px;
      content: "";
      position: absolute;
      top: 2px;
      left: 0;
    }
    .list {
      .item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: #ffffff;
        margin-top: 10px;
        padding: 16px 20px;
        .left {
          display: flex;
          flex-direction: column;
          font-size: 14px;
          font-weight: bold;
          line-height: 20px;
          color: #000000;
          .left-top {
            display: flex;
            align-items: center;
            .set {
              font-weight: 400;
              color: #fc7200;
              margin-left: 10px;
              cursor: pointer;
            }
          }
          .left-bot {
            margin-top: 2px;
            font-size: 12px;
            font-weight: 400;
            line-height: 17px;
            color: #999999;
          }
          .module-list {
            display: flex;
            align-items: center;
            margin-top: 10px;
            .module {
              position: relative;
              display: flex;
              align-items: center;
              justify-content: center;
              width: 250px;
              height: 150px;
              background: #f7f1f1;
              border-radius: 5px;
              cursor: pointer;
              margin-right: 20px;
              .module-status {
                position: absolute;
                top: 0;
                right: 0;
                color: #fc7200;
                font-size: 12px;
                font-weight: bold;
                padding: 4px;
              }
              .img-wrap {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 60px;
                height: 60px;
                background: #fc7200;
                border-radius: 50%;
                .img {
                  width: 30px;
                  height: 30px;
                }
              }
              .module-right {
                margin-left: 5px;

                .module-name {
                  font-size: 14px;
                  color: #666;
                }
                .module-tips {
                  font-size: 12px;
                  color: #999;
                  margin-top: 5px;
                }
              }
            }
          }
          .printer-list {
            display: flex;
            flex-wrap: wrap;
            .printer-item {
              position: relative;
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              width: 250px;
              height: 150px;
              background: #f7f1f1;
              border-radius: 8px;
              margin: 10px 20px 0 0;
              cursor: pointer;
              .img {
                width: 80px;
                height: 80px;
              }
              .name {
                font-size: 14px;
                font-weight: 500;
                line-height: 20px;
                color: #333333;
              }
              .shop-name {
                font-size: 12px;
                font-weight: 400;
                line-height: 20px;
                color: #999999;
              }
              .btns {
                position: absolute;
                top: 10px;
                right: 0;
                img {
                  width: 20px;
                  height: 20px;
                  margin-right: 10px;
                }
              }
            }
          }
        }
        .right {
          display: flex;
          align-items: center;
          .right-name {
            font-size: 13px;
            color: #fc7200;
            cursor: pointer;
          }
          .el-icon-arrow-right {
            color: #fc7200 !important;
            cursor: pointer;
          }
          .time {
            font-size: 12px;
            font-family: PingFang SC;
            font-weight: 400;
            line-height: 17px;
            color: #333333;
            margin-right: 20px;
          }
          .time1 {
            color: #999999;
          }
          .con {
            font-size: 14px;
            font-weight: 400;
            line-height: 20px;
            color: #fc7200;
            padding-left: 20px;
            cursor: pointer;
          }
          .con1 {
            color: #999999;
          }
        }
      }
    }
  }
}
.unify-phone {
  margin-top: 20px;
}
</style>