<template>
  <view class="printerList-container">
    <!-- <zTable
      :tableData="tableData"
      :columns="columns"
      titleTextAlign="center"
      textAlign="center"
    ></zTable> -->
    <u-navbar :autoBack="true" :safeAreaInsetTop="true" title="打印机列表">
      <template slot="right">
        <view
          v-if="tableData.length > 0"
          class="btn-addPrinter"
          @click="showPopup = true"
        >
          新增打印机
        </view>
      </template>
    </u-navbar>
    <u-search
      v-if="tableData.length > 0"
      class="search"
      placeholder="请输入打印机名字"
      :showAction="false"
      v-model="params.keyword"
      @input="searchOrder()"
    ></u-search>
    <scroll-view
      v-if="tableData.length > 0"
      class="uni-swiper-list"
      scroll-y
      :scroll-top="0"
      enhanced
      :show-scrollbar="false"
      @scrolltolower="scrolltolower"
    >
      <view class="table">
        <view class="table-title">
          <view
            class="table-title-item"
            v-for="(item, index) of columns"
            :key="index"
          >
            {{ item.title }}
          </view>
        </view>
        <view
          class="table-td"
          v-for="(item, index) of tableData"
          :key="index + item.num"
        >
          <view class="table-td-item table-td-name">
            {{ item.printer_name }}
          </view>
          <view class="table-td-item table-td-num">{{ item.printer_sn }}</view>
          <view class="table-td-item">
            <u-switch
              asyncChange
              @change="updatePrinterStatus($event, item)"
              v-model="item.status"
              activeColor="#5ac725"
              size="28"
              :activeValue="1"
              :inactiveValue="2"
            ></u-switch>
          </view>
          <view class="table-td-item table-td-operate">
            <u-icon
              class="fm-icon"
              custom-prefix="custom-icon-bianji custom-icon"
              size="25"
              color="#000"
              @click="showPopupModel(item)"
            ></u-icon>
            <u-icon
              class="fm-icon"
              custom-prefix="custom-icon-shanchu custom-icon"
              size="25"
              color="#000"
              @click="delectPrinter(item)"
            ></u-icon>
          </view>
        </view>
      </view>
      <view class="m-loading-box">
        <block v-if="isLoadingReachData">
          <view class="u-loadmore">
            <view class="u-loading"></view>
            <text class="u-loadmore-tips">正在加载...</text>
          </view>
        </block>
        <block v-else>
          <view class="u-loadmore u-loadmore-line">
            <text class="u-loadmore-tips">没有更多打印机啦！</text>
          </view>
        </block>
      </view>
    </scroll-view>
    <u-popup :show="showPopup" @close="close" :closeable="true">
      <view class="printer-popup">
        <u--form
          labelPosition="left"
          :model="form"
          :rules="rules"
          ref="uForm"
          label-width="100"
        >
          <u-form-item label="打印机名称" prop="printer_name" required>
            <u-input
              class="form-input"
              v-model="form.printer_name"
              placeholder="请输打印机名称"
            />
          </u-form-item>
          <u-form-item
            label="设备品牌"
            prop="model_name"
            required
            @click="getPrinterModelList"
          >
            <u--input
              v-model="form.model_name"
              disabled
              disabledColor="#ffffff"
              placeholder="请选择打印机品牌"
            ></u--input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          <u-form-item label="打印机编号" prop="printer_sn" required>
            <u-input
              class="form-input"
              v-model="form.printer_sn"
              placeholder="请输打印机编号"
            />
          </u-form-item>
          <u-form-item label="打印机密钥" prop="printer_key" required>
            <u-input
              class="form-input"
              v-model="form.printer_key"
              placeholder="请输打印机密钥"
            />
          </u-form-item>
          <u-form-item label="URL" prop="website_url" required>
            <u-input
              class="form-input"
              v-model="form.website_url"
              placeholder="例如:www.test.com"
            />
          </u-form-item>
          <u-form-item label="打印来源" prop="">
            <u-radio-group v-model="form.flag" placement="row">
              <u-radio
                class="printer-radio-item"
                v-for="(item, index) of radioGroup"
                :key="index"
                activeColor="#2979ff"
                :label="item.region"
                :name="item.region_id"
              ></u-radio>
            </u-radio-group>
          </u-form-item>
          <u-form-item label="纸张宽度" prop="">
            <u-radio-group v-model="form.paper_with" placement="row">
              <u-radio
                class="printer-radio-item"
                activeColor="#2979ff"
                label="58mm"
                :name="58"
              ></u-radio>
              <u-radio
                class="printer-radio-item"
                activeColor="#2979ff"
                label="80mm"
                :name="80"
              ></u-radio>
            </u-radio-group>
          </u-form-item>
          <view class="tips">
            * 80mm宽度仅支持“飞蛾打印机（新接口）”“芯烨云打印机”两种品牌。
          </view>
        </u--form>
        <view class="btn-content">
          <u-button class="btn-next" @click="submit">
            {{ isAdd ? "添加" : "修改" }}
          </u-button>
        </view>
      </view>
    </u-popup>
    <view class="no-data" v-if="tableData.length <= 0 && !loading">
      <view class="no-data-bg"></view>
      <view class="nodata-tips">暂无打印机!</view>
      <view class="btn" @click="showPopup = true">立即添加</view>
    </view>
    <u-picker
      class="u-printer-picker"
      v-if="showbrandList"
      mode="selector"
      :show="showbrandList"
      :safe-area-inset-bottom="true"
      :default-selector="[0]"
      :columns="brandList"
      :keyName="'model_name'"
      @cancel="handleCancel"
      @confirm="handleConfirm"
    ></u-picker>
  </view>
</template>

<script>
import {
  GetPrinterList,
  GetPrinterflagList,
  GetPrinterModelList,
  AddPrinter,
  DelectPrinter,
  UpdatePrinter,
  UpdatePrinterStatus,
  TestPrinter,
} from "../../../api/printer";
import zTable from "../../../components/table/z-table.vue";
// import UButton from "../../../uni_modules/uview-ui/components/u-button/u-button.vue";
export default {
  components: {
    zTable,
  },
  data() {
    return {
      params: {
        keyword: "",
        pageNum: 1,
        pageSize: 20,
      },
      printerList: [],
      tableData: [],
      columns: [
        {
          title: "打印机名称",
          listenerClick: true,
          key: "name",
        },
        {
          title: "编号",
          key: "num",
        },
        {
          title: "状态",
          key: "status",
        },
        {
          title: "操作",
          key: "operate",
        },
      ],
      showPopup: false,
      isAdd: true,
      popupInfo: {},
      form: {
        printer_name: "",
        model_name: "",
        printer_sn: "",
        printer_key: "",
        website_url: "",
        region: 0,
        paper_with: 58,
        flag: 1,
      },
      rules: {
        printer_name: {
          type: "string",
          required: true,
          message: "请输入打印机名称",
          trigger: ["blur", "change"],
        },
      },
      radioGroup: [
        {
          key: 1,
          name: "收银台",
        },
        {
          key: 2,
          name: "核销处",
        },
        {
          key: 3,
          name: "网店",
        },
      ],
      params: {
        keyword: "",
        pageNum: 1,
        pageSize: 10,
      },

      isLoadingReachData: false,
      searchTime: 0,
      showbrandList: false,
      brandList: [[0]],
      loading: true,
    };
  },
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
  },
  onShow() {
    this.getPrinterList();
    this.getPrinterflagList();
  },
  methods: {
    async getPrinterList() {
      let res = await GetPrinterList(this.params);
      if (res && res.status == 200) {
        if (this.isLoadingReachData) {
          if (res.data.items.length > 0) {
            this.isLoadingReachData = false;
            return;
          } else {
            this.tableData = [...this.tableData, ...res.data.item];
          }
        } else {
          this.tableData = res.data.items;
        }
      }
      this.isLoadingReachData = false;
      this.loading = false;
    },
    async getPrinterflagList() {
      let res = await GetPrinterflagList({ count: 99 });
      if (res && res.status == 200) {
        this.radioGroup = res.data;
      }
    },
    async getPrinterModelList() {
      let res = await GetPrinterModelList({ count: 99 });
      if (res && res.status == 200) {
        this.brandList[0] = res.data;
        this.showbrandList = true;
      }
    },
    showPopupModel(item) {
      this.isAdd = false;
      setTimeout(() => {
        this.$refs["uForm"].setRules(this.rules);
      }, 0);

      this.showPopup = true;
      this.form = item;
    },
    handleCancel() {
      this.showbrandList = false;
    },
    handleConfirm(e) {
      this.form.model_id = e.value[0].model_id;
      this.showbrandList = false;
    },
    close() {
      this.showPopup = false;
    },
    searchOrder() {
      this.params.pageNum = 1;
      this.params.pageSize = 10;
      clearTimeout(this.searchTime);
      this.searchTime = setTimeout(() => {
        this.getPrinterList();
      }, 600);
    },
    scrolltolower() {
      this.isLoadingReachData = true;
      clearTimeout(this.searchTime);
      this.searchTime = setTimeout(() => {
        this.getPrinterList();
      }, 600);
    },
    async updatePrinterStatus(value, item) {
      let params = {
        printer_id: item.printer_id,
        status: value,
      };
      if (value == 2) {
        uni.showModal({
          title: "提示",
          content: `你确认要禁用打印机？`,
          success: async (res) => {
            if (res.confirm) {
              let res = await UpdatePrinterStatus(params);
              if (res && res.status == 200) {
                item.status = value;
                uni.showToast({
                  title: `禁用成功`,
                  icon: "success",
                  duration: 600,
                });
              }
            } else if (res.cancel) {
              // 用户点击了取消按钮
            }
          },
        });
      } else {
        let res = await UpdatePrinterStatus(params);
        if (res && res.status == 200) {
          item.status = value;
          uni.showToast({
            title: `禁用成功`,
            icon: "success",
            duration: 600,
          });
        }
      }
    },
    async submit() {
      let params = JSON.parse(JSON.stringify(this.form));
      if (this.isAdd) {
        let res = await AddPrinter(params);
        if (res.status == 200) {
          this.close();
          uni.showToast({
            title: `添加成功`,
            icon: "success",
            duration: 600,
          });
        }
      } else {
        let res = await UpdatePrinter(params);
        if (res.status == 200) {
          this.close();
          uni.showToast({
            title: `修改成功`,
            icon: "success",
            duration: 600,
          });
        }
      }
      this.getPrinterList();
    },
    delectPrinter(item) {
      uni.showModal({
        title: "警告",
        content: `你确认要删除打印机？`,
        success: async (res) => {
          if (res.confirm) {
            let res = await DelectPrinter({
              printer_id: item.printer_id,
            });
            if (res && res.status == 200) {
              uni.showToast({
                title: `删除成功`,
                icon: "success",
                duration: 600,
              });
              this.params = {
                keyword: "",
                pageNum: 1,
                pageSize: 10,
              };
              this.getPrinterList();
            }
          } else if (res.cancel) {
            // 用户点击了取消按钮
          }
        },
      });
    },
  },
};
</script>

<style lang="scss">
@import "@/styles/variables.scss";
.printerList-container {
  overflow: hidden;

  .btn-addPrinter {
    color: $base-color;
  }

  .search {
    margin: 40rpx !important;
    margin-top: 120rpx !important;
  }

  .uni-swiper-list {
    height: calc(100vh - 165px);
  }

  .table {
    .table-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 24rpx;
      padding-right: 52rpx;
      height: 80rpx;
      background: #f2f2f2;
      color: #aaaaaa;
      font-size: 28rpx;
    }

    .table-td-name {
      min-width: 160rpx;
      max-width: 160rpx;
      word-wrap: break-word;
    }

    .table-td-num {
      min-width: 160rpx;
      max-width: 160rpx;
      word-wrap: break-word;
      text-align: center;
    }

    .table-td {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 24rpx;
      margin: 40rpx 0;

      .table-td-item {
      }
    }

    .table-td-operate {
      display: flex;
      width: 120rpx;
      justify-content: space-between;
    }
  }

  .printer-popup {
    padding: 92rpx 40rpx 36rpx;

    .form {
      padding: 0 36rpx;
      background: red;
      border-top: 1px solid #f2f2f2;

      .printer-popup {
        background: red;
      }

      ::v-deep.printer-radio-item {
        margin-right: 20rpx;
      }
    }

    ::v-deep.u-form-item__body__right__content__slot {
      .u-radio-group {
        .printer-radio-item {
          margin-right: 56rpx;
        }
      }
    }

    ::v-deep.u-form-item__body__left {
      // min-width: 200rpx;
    }
  }

  .tips {
    font-size: 20rpx;
    color: #aaaaaa;
  }

  .btn-content {
    bottom: 40rpx;
    width: 94%;
    padding: 48rpx 24rpx;
  }

  .btn-next {
    border-radius: 16rpx;
    background: $base-color;
    color: #fff;
  }

  .m-loading-box {
    text-align: center;
    margin: 40rpx;
    color: #aaaa;
    font-size: 28rpx;
  }

  .no-data {
    .no-data-bg {
      width: 600rpx;
      height: 600rpx;
      margin: 80rpx auto;
      background-image: url("../../../static/no-data.png");
      background-size: 100% 100%;
    }

    .nodata-tips {
      font-size: 28rpx;
      text-align: center;
      color: #aaaaaa;
    }

    .btn {
      margin: 80rpx auto;
      width: 50%;
      height: 100rpx;
      line-height: 100rpx;
      text-align: center;
      font-size: 36rpx;
      background: $base-color;
      border-radius: 64rpx;
      color: #fff;
    }
  }

  .u-printer-picker {
    ::v-deep.u-transition {
      z-index: 10075 !important;
    }
  }
}
</style>
