<template>
  <div class="main_root">
    <div class="search_header">
      <Input
        v-model="searchForm.name"
        placeholder="请输入壁纸名称"
        search
        @on-search="searchList()"
        style="width: 150px"
      />
      <Button
        v-if="add_has === 1"
        type="primary"
        class="primary_btn"
        @click="toAdd()"
        >新建</Button
      >
    </div>
    <div class="table_wrap">
      <Table :columns="columns" :data="searchForm.list">
        <template slot-scope="{ row }" slot="hpath">
          <div class="hpath">
            <img v-if="row.hpath" :src="$api.showImageUrl + row.hpath" />
          </div>
        </template>
        <template slot-scope="{ row }" slot="vpath">
          <div class="hpath">
            <img v-if="row.vpath" :src="$api.showImageUrl + row.vpath" />
          </div>
        </template>
        <template slot-scope="{ row }" slot="actionSlot">
          <div class="action_list">
            <div @click="toView(row)">查看</div>
            <div @click="toEdit(row)">编辑</div>
            <div class="action_del" @click="toDel(row)">删除</div>
          </div>
        </template>
      </Table>
    </div>
    <div class="page_wrap">
      <Page
        :transfer="true"
        :total="searchForm.total"
        :current="searchForm.page"
        :page-size="searchForm.size"
        :page-size-opts="[10, 20, 40, 60]"
        @on-change="pageChange"
        @on-page-size-change="pageSizeChange"
        show-total
        show-sizer
      ></Page>
    </div>
    <!-- 新建 -->
    <Modal
      class="modal1"
      :mask-closable="false"
      v-model="wallpaperInfo.show"
      :title="wallpaperInfo.wallpaperid ? '编辑' : '新建'"
    >
      <Form
        v-if="wallpaperInfo.show"
        ref="addForm"
        :model="wallpaperInfo"
        :rules="rules"
        :label-width="100"
        inline
      >
        <FormItem label="名称" prop="wname" style="width: 100%">
          <Input
            v-model="wallpaperInfo.wname"
            placeholder="请输入壁纸名称"
          ></Input>
        </FormItem>
        <FormItem label="壁纸" class="require" style="width: 100%">
          <div class="wallpaper_upload_box">
            <div class="wallpaper_h">
              <Upload
                action
                :show-upload-list="false"
                class="wallpaper_upload"
                :before-upload="
                  (file) => {
                    upLoad(file, 1);
                    return false;
                  }
                "
                accept=".png,.jpeg,.jpg"
              >
                <div class="wallpaper_img_box" v-if="wallpaperInfo.hpath">
                  <img :src="$api.showImageUrl + wallpaperInfo.hpath" />
                </div>
                <div v-else class="upload_tip">
                  <div>
                    <Icon type="ios-cloud-upload-outline" size="42"></Icon>
                    <div>横屏壁纸</div>
                  </div>
                </div>
              </Upload>
            </div>
            <div class="wallpaper_v">
              <Upload
                action
                :show-upload-list="false"
                class="wallpaper_upload"
                :before-upload="
                  (file) => {
                    upLoad(file, 2);
                    return false;
                  }
                "
                accept=".png,.jpeg,.jpg"
              >
                <div class="wallpaper_img_box" v-if="wallpaperInfo.vpath">
                  <img :src="$api.showImageUrl + wallpaperInfo.vpath" />
                </div>
                <div v-else class="upload_tip">
                  <div>
                    <Icon type="ios-cloud-upload-outline" size="42"></Icon>
                    <div>竖屏壁纸</div>
                  </div>
                </div>
              </Upload>
            </div>
            <div class="wallpaper_tip">
              <div>支持格式：jpg、jpeg、png</div>
              <div>最大限制：2MB</div>
            </div>
          </div>
        </FormItem>
        <FormItem label="授权型号" class="require" style="width: 100%">
          <div v-for="item in device_list" :key="item.dgroupid">
            <CheckboxDevice
              @CheckboxDevice="CheckboxDevice"
              :dgroupid="item.dgroupid"
              ref="checkbevice"
              :module="item"
            ></CheckboxDevice>
          </div>
        </FormItem>
      </Form>
      <div slot="footer">
        <div>
          <Button @click="wallpaperInfo.show = false">取消</Button>
          <Button @click="saveAddInfo()" class="primary_btn" type="primary"
            >保存</Button
          >
        </div>
      </div>
    </Modal>
    <!-- 查看 -->
    <Modal
      class="modal1 view"
      :mask-closable="false"
      v-model="viewInfo.show"
      title="查看"
    >
      <div class="view_titles">{{ viewInfo.wname }}</div>
      <div class="view_content">
        <div class="view_title">壁纸效果</div>
        <div class="view_wallpaper_box">
          <div class="view_img_box h" v-if="viewInfo.hpath">
            <img :src="$api.showImageUrl + viewInfo.hpath" />
          </div>
          <div class="view_img_box v" v-if="viewInfo.vpath">
            <img :src="$api.showImageUrl + viewInfo.vpath" />
          </div>
        </div>
      </div>
      <div class="view_content" style="margin-top: 20px">
        <div class="view_title">授权型号</div>
        <div class="view_devices">
          <div
            class="view_list"
            v-for="item in viewInfo.devices"
            :key="item.dgroupid"
          >
            <div class="dgname">{{ item.dgname }}</div>
            <div class="devices">
              <span v-for="sitem in item.devices" :key="sitem.deviceid">{{
                sitem.deviceModel
              }}</span>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" style="text-align: center">
        <Button @click="viewInfo.show = false">关闭</Button>
      </div>
    </Modal>
    <Spin fix v-if="showLoading" style="background-color: transparent">
      <Icon type="ios-loading" size="18" class="demo-spin-icon-load"></Icon>
      <div>加载中</div>
    </Spin>
  </div>
</template>

<script>
import axios from "axios";
import CheckboxDevice from "@/components/Checkbox/CheckboxDevice";
import {
  wallpaper_add,
  wallpaper_add_has,
  wallpaper_delete,
  wallpaper_detail,
  wallpaper_edit,
  wallpaper_list,
  wallpaper_list_device,
  wallpaper_list_devicewp
} from "@/api/setting";
export default {
  components: {
    CheckboxDevice
  },
  data() {
    return {
      showLoading: false,
      searchForm: {
        name: "",
        page: 1,
        size: 10,
        list: [],
        total: 0
      },
      // 新建/编辑
      wallpaperInfo: {
        show: false,
        id: null,
        wname: "",
        hpath: "",
        vpath: "",
        wlevel: "",
        objectid: "",
        deviceids: []
      },
      // 查看
      viewInfo: {
        show: false,
        name: ""
      },
      rules: {
        wname: [
          {
            required: true,
            message: "请输入壁纸名称",
            trigger: "blur"
          }
        ]
      },
      userInfo: {},
      device_list: [],
      deviceids: {}, //设备类型
      add_has: 0,
      columns: [
        {
          title: "序号",
          align: "center",
          width: 70,
          render: (h, params) => {
            return h(
              "span",
              params.index +
                (this.searchForm.page - 1) * this.searchForm.size +
                1
            );
          }
        },
        {
          title: "横屏壁纸",
          slot: "hpath",
          align: "center"
        },
        {
          title: "竖屏壁纸",
          slot: "vpath",
          align: "center"
        },
        {
          title: "壁纸名称",
          key: "wname",
          align: "center"
        },
        {
          title: "操作人",
          key: "updatename",
          align: "center"
        },
        {
          title: "操作时间",
          key: "updatetime",
          width: 190,
          align: "center"
        },
        {
          title: "操作",
          slot: "actionSlot",
          width: 220,
          align: "center"
        }
      ]
    };
  },
  computed: {
    powerParams() {
      return this.$store.getters.powerParams;
    }
  },
  created() {
    this.userInfo = JSON.parse(
      localStorage.getItem("xh_control_userInfo")
    ).content;
    this.init();
    this.searchList();
  },
  methods: {
    CheckboxDevice(dgroupid, val) {
      this.deviceids[dgroupid] = val;
    },
    async init() {
      //是否显示添加按钮
      this.showLoading = true;
      let res = await wallpaper_add_has({
        wlevel: 2,
        objectid: this.powerParams.objectid
      });
      this.showLoading = false;
      if (res.code === 0) {
        this.add_has = res.obj;
      } else {
        this.$Message.error(res.msg);
      }
    },
    upLoad(file, type) {
      //type 1横屏 2竖屏
      let str = file.name.split(".");
      let size = file.size / 1024 / 1024;
      let suffix = str[str.length - 1];
      suffix = suffix.toLowerCase();
      if (
        suffix !== "png" &&
        suffix !== "jpeg" &&
        suffix !== "jpg"
      ) {
        this.$Message.warning("请上传png、jpeg、jpg类型的文件");
        return false;
      }
      if (size > 2) {
        this.$Message.error("图片太大，不能超过2M！");
        return false;
      }
      let formData = new FormData();
      formData.append("file", file);
      formData.append("savefolder", "wallpaper");
      formData.append("isrename", "1");
      let Url = this.$api.baseImageUrl + "up/upfile";
      this.showLoading = true;
      axios
        .post(Url, formData, {
          timeout: 1000 * this.$api.axiosFileTimeout
        })
        .then((res) => {
          this.showLoading = false;
          if (res.data.code === 0) {
            if (type === 1) {
              this.wallpaperInfo.hpath = res.data.obj;
            } else {
              this.wallpaperInfo.vpath = res.data.obj;
            }
            this.$Message.success(res.data.msg);
          } else {
            this.$Message.error(res.data.msg);
          }
        })
        .catch(() => {
          this.showLoading = false;
          this.$Message.error("壁纸上传失败");
        });
    },
    // 搜索
    searchList() {
      this.searchForm.page = 1;
      this.getList();
    },
    // 页码改变
    pageChange(page) {
      this.searchForm.page = page;
      this.getList();
    },
    // 每页显示数量改变
    pageSizeChange(size) {
      this.searchForm.size = size;
      this.searchForm.page = 1;
      this.getList();
    },
    // 获取列表
    getList() {
      this.showLoading = true;
      wallpaper_list({
        page: this.searchForm.page,
        size: this.searchForm.size,
        name: this.searchForm.name,
        rtype: this.powerParams.rtype,
        objectid: this.powerParams.objectid
      }).then((data) => {
        this.showLoading = false;
        if (data.code === 0) {
          this.searchForm.list = data.obj.data;
          this.searchForm.total = data.obj.total;
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    // 新建
    toAdd() {
      this.showLoading = true;
      wallpaper_list_device({
        wlevel: 2,
        objectid: this.powerParams.objectid
      }).then((res) => {
        this.showLoading = false;
        if (res.code === 0) {
          this.device_list = res.obj;
          this.wallpaperInfo = {
            show: true,
            id: null,
            wname: "",
            hpath: "",
            vpath: "",
            wlevel: "",
            objectid: "",
            deviceids: []
          };
        } else {
          this.$Message.error(res.msg);
        }
      });
    },
    // 保存新建
    saveAddInfo() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          //获取选中设备
          let deviceids = [];
          for (let key in this.deviceids) {
            for (let deviceid of this.deviceids[key]) {
              deviceids.push(deviceid);
            }
          }
          if (deviceids.length === 0) {
            this.$Message.error("请选择设备!");
            return;
          }
          if (!this.wallpaperInfo.hpath && !this.wallpaperInfo.vpath) {
            this.$Message.error("请上传壁纸!");
            return;
          }
          let api = this.wallpaperInfo.wallpaperid
            ? wallpaper_edit
            : wallpaper_add;
          let form = {
            wname: this.wallpaperInfo.wname,
            hpath: this.wallpaperInfo.hpath,
            vpath: this.wallpaperInfo.vpath,
            wlevel: 2,
            rtype: this.powerParams.rtype,
            objectid: this.powerParams.objectid,
            deviceids
          };
          if (this.wallpaperInfo.wallpaperid) {
            //编辑
            form.rversion = this.wallpaperInfo.rversion;
            form.wallpaperid = this.wallpaperInfo.wallpaperid;
          }
          this.showLoading = true;
          api(form).then((data) => {
            this.showLoading = false;
            if (data.code === 0) {
              this.wallpaperInfo.show = false;
              this.init();
              this.searchList();
              this.$Message.success(data.msg);
            } else {
              this.$Message.error(data.msg);
            }
          });
        }
      });
    },
    // 查看
    toView(row) {
      this.showLoading = true;
      wallpaper_detail({
        rtype: this.powerParams.rtype,
        objectid: this.powerParams.objectid,
        wallpaperid: row.wallpaperid
      }).then((data) => {
        this.showLoading = false;
        if (data.code === 0) {
          this.viewInfo = {
            show: true,
            wname: data.obj.wname,
            hpath: data.obj.hpath,
            vpath: data.obj.vpath,
            devices: data.obj.devices
          };
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    // 编辑
    async toEdit(row) {
      this.showLoading = true;
      //获取选择设备包含自己
      let res1 = await wallpaper_list_devicewp({
        wlevel: this.powerParams.rtype,
        objectid: this.powerParams.objectid,
        wallpaperid: row.wallpaperid
      });
      if (res1.code === 0) {
        this.device_list = res1.obj;
      } else {
        this.$Message.error(res1.msg);
      }
      //获取详情
      let res = await wallpaper_detail({
        rtype: this.powerParams.rtype,
        objectid: this.powerParams.objectid,
        wallpaperid: row.wallpaperid
      });
      this.showLoading = false;
      if (res.code === 0) {
        this.wallpaperInfo = {
          show: true,
          wallpaperid: res.obj.wallpaperid,
          wname: res.obj.wname,
          hpath: res.obj.hpath,
          vpath: res.obj.vpath,
          wlevel: res.obj.wlevel,
          objectid: res.obj.objectid,
          deviceids: res.obj.devices,
          rversion: res.obj.rversion
        };
        this.$nextTick(() => {
          //回显设备
          let checkedArr = this.$refs.checkbevice;
          if (checkedArr) {
            for (let m = 0; m < checkedArr.length; m++) {
              let dgroupid = checkedArr[m].module.dgroupid;
              let marr = res.obj.devices;
              for (let h = 0; h < marr.length; h++) {
                let arr = marr[h].devices;
                if (dgroupid == marr[h].dgroupid) {
                  checkedArr[m].getCheckedDevices(arr);
                }
              }
            }
          }
        });
      } else {
        this.$Message.error(res.msg);
      }
    },
    // 删除
    toDel(row) {
      this.$Modal.confirm({
        title: "提示",
        content: "您确定删除选中数据吗？",
        onOk: () => {
          wallpaper_delete({
            rtype: this.powerParams.rtype,
            objectid: this.powerParams.objectid,
            wallpaperid: row.wallpaperid,
            rversion: row.rversion
          }).then((data) => {
            if (data.code === 0) {
              this.searchList();
              this.$Message.success(data.msg);
            } else {
              this.$Message.error(data.msg);
            }
          });
        },
        onCancel: () => {}
      });
    }
  }
};
</script>

<style lang="less" scoped>
.search_header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 16px 16px;
}
.view {
  .view_titles {
    margin-bottom: 16px;
    font-size: 18px;
    font-weight: bold;
    text-align: center;
  }
  .view_content {
    display: flex;
    .view_title {
      width: 70px;
      flex: none;
      margin: 0 10px;
    }
    .view_wallpaper_box {
      display: flex;
      justify-content: flex-start;
      align-items: flex-end;
      .view_img_box {
        position: relative;
        margin-right: 20px;
        border-radius: 6px;
        border: 5px solid #333;
        background: #f0f6fc;
        &.h {
          width: 180px;
          height: 120px;
          img {
            width: 100%;
            height: 100%;
          }
        }
        &.v {
          width: 120px;
          height: 180px;
          img {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
    .view_devices {
      .view_list {
        margin-bottom: 20px;
      }
      .dgname {
        line-height: 30px;
      }
      .devices {
        display: flex;
        flex-wrap: wrap;
        span {
          margin-right: 20px;
          margin-bottom: 10px;
        }
      }
    }
  }
}

.table_wrap {
  .hpath {
    max-width: 100px;
    max-height: 60px;
    margin: 10px auto;
    img {
      max-width: 100px;
      max-height: 60px;
    }
  }
}
.wallpaper_upload_box {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  .wallpaper_h {
    position: relative;
    margin-top: 60px;
    margin-right: 50px;
    width: 190px;
    height: 130px;
    border-radius: 6px;
    opacity: 1;
    border: 5px solid #333;
    background: #f0f6fc;
    &:hover {
      background: #eaf5ff;
      .upload_tip {
        color: #339cff !important;
      }
    }
    .wallpaper_upload {
      width: 180px;
      height: 120px;
      cursor: pointer;
      .wallpaper_img_box {
        width: 180px;
        height: 120px;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .upload_tip {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 180px;
        height: 120px;
        text-align: center;
        color: #b8c2d9;
      }
    }
  }
  .wallpaper_v {
    position: relative;
    margin-right: 20px;
    width: 130px;
    height: 190px;
    border-radius: 6px;
    opacity: 1;
    border: 5px solid #333;
    background: #f0f6fc;
    &:hover {
      background: #eaf5ff;
      .upload_tip {
        color: #339cff !important;
      }
    }
    .wallpaper_upload {
      width: 120px;
      height: 180px;
      cursor: pointer;
      .wallpaper_img_box {
        width: 120px;
        height: 180px;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .upload_tip {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 120px;
        height: 180px;
        text-align: center;
        color: #b8c2d9;
      }
    }
  }
  .wallpaper_tip {
    font-size: 16px;
    color: #7c8db5;
  }
}
</style>
