<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="searchForm.list.length === 0"
        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="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="壁纸" style="width: 100%">
          <div class="up">
            <Upload
              class="Upload"
              action
              :show-upload-list="false"
              :before-upload="
                (file) => {
                  upLoad(file);
                  return false;
                }
              "
              accept=".png,.jpeg,.jpg,.gif"
            >
              <div v-if="!wallpaperInfo.hpath" class="icon">横屏壁纸</div>
              <div v-else class="hpath">
                <img :src="$api.showImageUrl + wallpaperInfo.hpath" />
              </div>
            </Upload>
            <span>支持图片格式：jpg、jgeg、gif、png</span>
          </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="hpath">
          <img :src="$api.showImageUrl + viewInfo.hpath" />
        </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_delete,
  wallpaper_detail,
  wallpaper_edit,
  wallpaper_list
} from "@/api/setting";
import { device_list } from "@/api/appgroup";
export default {
  components: {
    CheckboxDevice
  },
  data() {
    return {
      showLoading: false,
      searchForm: {
        name: "",
        page: 1,
        size: 10,
        list: [],
        total: 0
      },
      // 新建
      wallpaperInfo: {
        show: false,
        id: null,
        wname: "",
        hpath: "",
        wlevel: "",
        objectid: "",
        deviceids: []
      },
      // 编辑
      modifyRegion: {
        show: false,
        regionid: null,
        name: "",
        regionCode: "",
        comm: "",
        rversion: null
      },
      // 查看
      viewInfo: {
        show: false,
        name: ""
      },
      rules: {
        wname: [
          {
            required: true,
            message: "请输入区域名称",
            trigger: "blur"
          }
        ]
      },
      userInfo: {},
      device_list: [],
      deviceids: {}, //设备类型
      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: "壁纸名称",
          key: "wname",
          align: "center"
        },
        {
          title: "操作人",
          key: "updatename",
          align: "center"
        },
        {
          title: "操作时间",
          key: "updatetime",
          width: 190,
          align: "center"
        },
        {
          title: "操作",
          slot: "actionSlot",
          width: 220,
          align: "center"
        }
      ]
    };
  },
  created() {
    this.userInfo = JSON.parse(
      localStorage.getItem("xh_control_userInfo")
    ).content;
    this.init();
    this.searchList();
  },
  methods: {
    CheckboxDevice(dgroupid, val) {
      this.deviceids[dgroupid] = val;
    },
    init() {
      //获取分组下设备
      this.showLoading = true;
      device_list({}).then((res) => {
        this.showLoading = false;
        if (res.code === 0) {
          this.device_list = res.obj;
        } else {
          this.$Message.error(res.msg);
        }
      });
    },
    upLoad(file) {
      let str = file.name.split(".");
      let suffix = str[str.length - 1];
      suffix = suffix.toLowerCase();
      if (suffix !== "png" && suffix !== "jpeg" && suffix !== "jpg") {
        this.$Message.warning("请上传png、jpeg、jpg类型的文件");
        return false;
      }
      let formData = new FormData();
      formData.append("file", file);
      formData.append("savefolder", "app");
      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) {
            this.wallpaperInfo.hpath = 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,
        regionid: this.userInfo.regionid
      }).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.wallpaperInfo = {
        show: true,
        id: null,
        wname: "",
        hpath: "",
        wlevel: "",
        objectid: "",
        deviceids: []
      };
    },
    // 保存新建
    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.$Message.error("请上传横屏壁纸!");
            return;
          }
          let api = this.wallpaperInfo.wallpaperid
            ? wallpaper_edit
            : wallpaper_add;
          let form = {
            wname: this.wallpaperInfo.wname,
            hpath: this.wallpaperInfo.hpath,
            wlevel: 2,
            objectid: this.userInfo.regionid,
            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.searchList();
              this.$Message.success(data.msg);
            } else {
              this.$Message.error(data.msg);
            }
          });
        }
      });
    },
    // 查看
    toView(row) {
      this.showLoading = true;
      wallpaper_detail({
        wallpaperid: row.wallpaperid
      }).then((data) => {
        this.showLoading = false;
        if (data.code === 0) {
          this.viewInfo = {
            show: true,
            wname: data.obj.wname,
            hpath: data.obj.hpath,
            devices: data.obj.devices
          };
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    // 编辑
    toEdit(row) {
      this.showLoading = true;
      wallpaper_detail({
        wallpaperid: row.wallpaperid
      }).then((data) => {
        this.showLoading = false;
        if (data.code === 0) {
          this.wallpaperInfo = {
            show: true,
            wallpaperid: data.obj.wallpaperid,
            wname: data.obj.wname,
            hpath: data.obj.hpath,
            wlevel: data.obj.wlevel,
            objectid: data.obj.objectid,
            deviceids: data.obj.devices,
            rversion: data.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 = data.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(data.msg);
        }
      });
      this.wallpaperInfo = {
        show: true,
        // 验证码计时
        timer: null,
        name: "",
        img: ""
      };
    },
    // 删除
    toDel(row) {
      this.$Modal.confirm({
        title: "提示",
        content: "您确定删除选中数据吗？",
        onOk: () => {
          wallpaper_delete({
            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;
    }
    .hpath {
      width: 180px;
      height: 120px;
      border-radius: 8px;
      overflow: hidden;
      border: 3px solid #333333;
      background-color: #f0f6fc;
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    .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 {
    width: 100px;
    height: 60px;
    margin: 10px auto;
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
}
.up {
  display: flex;
  .Upload {
    width: 180px;
    height: 120px;
    border-radius: 8px;
    border: 3px solid #333333;
    background-color: #f0f6fc;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    .icon {
      color: #b8c2d9;
    }
    .hpath {
      width: 180px;
      height: 120px;
      border-radius: 8px;
      overflow: hidden;
      padding: 3px;
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }
  span {
    margin-left: 20px;
    color: #7c8db5;
    font-size: 16px;
  }
}
</style>
