<template>
  <div class="main_root">
    <div class="search_header">
      <Input
        v-model="searchForm.name"
        placeholder="请输入壁纸名称"
        search
        @on-search="searchList()"
        style="width: 150px"
      />
      <Button type="primary" class="primary_btn" @click="toAdd()">新建</Button>
    </div>
    <div class="table_wrap">
      <Table :columns="columns" :data="searchForm.list">
        <div
          slot-scope="{ row }"
          slot="hpathSlot"
          style="display: flex; justify-content: center; align-items: center"
        >
          <img
            style="
              margin: 4px 0;
              max-width: 100px;
              max-height: 56px;
              object-fit: contain;
            "
            v-if="row.hpath"
            :src="$api.showImageUrl + row.hpath"
          />
        </div>
        <div
          slot-scope="{ row }"
          slot="vpathSlot"
          style="display: flex; justify-content: center; align-items: center"
        >
          <img
            style="
              margin: 4px 0;
              max-width: 100px;
              max-height: 56px;
              object-fit: contain;
            "
            v-if="row.vpath"
            :src="$api.showImageUrl + row.vpath"
          />
        </div>
        <template slot-scope="{ row }" slot="actionSlot">
          <div class="action_list">
            <div @click="toView(row)">查看</div>
            <div v-if="userInfo.adminid === row.updateid" @click="toEdit(row)">
              编辑
            </div>
            <div
              v-if="userInfo.adminid === row.updateid"
              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="80"
      >
        <FormItem label="名称" prop="wname">
          <Input v-model="wallpaperInfo.wname" placeholder="请输入名称"></Input>
        </FormItem>
        <FormItem label="壁纸" class="require">
          <div class="wallpaper_upload_box">
            <div class="wallpaper_h">
              <Upload
                action
                :show-upload-list="false"
                class="wallpaper_upload"
                :before-upload="
                  (file) => {
                    upLoadHWallpaper(file);
                    return false;
                  }
                "
                accept=".png,.jpeg,.jpg,.gif"
              >
                <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>
              <Spin fix v-if="wallpaperInfo.hLoading">
                <Icon
                  type="ios-loading"
                  size="18"
                  class="demo-spin-icon-load"
                ></Icon>
                <div>加载中</div>
              </Spin>
            </div>
            <div class="wallpaper_v">
              <Upload
                action
                :show-upload-list="false"
                class="wallpaper_upload"
                :before-upload="
                  (file) => {
                    upLoadVWallpaper(file);
                    return false;
                  }
                "
                accept=".png,.jpeg,.jpg,.gif"
              >
                <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>
              <Spin fix v-if="wallpaperInfo.vLoading">
                <Icon
                  type="ios-loading"
                  size="18"
                  class="demo-spin-icon-load"
                ></Icon>
                <div>加载中</div>
              </Spin>
            </div>
            <div class="wallpaper_tip">
              <div>支持格式：jpg、jpeg、gif、png</div>
              <div>最大限制：2MB</div>
            </div>
          </div>
        </FormItem>
        <FormItem label="适配类型">
          <div
            class="device_brand"
            v-for="brandItem in wallpaperInfo.deviceList"
            :key="brandItem.dgroupid"
          >
            <div class="device_brand_header">
              <div class="drop_icon_box" @click="toCloseDeviceBrand(brandItem)">
                <Icon
                  :class="[
                    'drop_icon',
                    brandItem.close ? 'arrow_dropdown' : ''
                  ]"
                  type="md-arrow-dropdown"
                  :size="20"
                />
              </div>
              <Checkbox
                :disabled="brandItem.devices.length === 0"
                :indeterminate="
                  getIndeterminate(brandItem, wallpaperInfo.deviceids)
                "
                :value="getCheckedAllValue(brandItem, wallpaperInfo.deviceids)"
                @click.prevent.native="
                  deviceBrandCheckedAll(
                    brandItem,
                    getCheckedAllValue(brandItem, wallpaperInfo.deviceids)
                  )
                "
                >{{ brandItem.dgname }}</Checkbox
              >
            </div>
            <div class="device_brand_main" v-if="!brandItem.close">
              <Checkbox
                v-for="deviceItem in brandItem.devices"
                :key="deviceItem.deviceid"
                :value="wallpaperInfo.deviceids.includes(deviceItem.deviceid)"
                @on-change="deviceModelCheck(deviceItem)"
                >{{ deviceItem.deviceModel }}</Checkbox
              >
            </div>
          </div>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="wallpaperInfo.show = false">取消</Button>
        <Button @click="saveAddInfo()" class="primary_btn" type="primary"
          >保存</Button
        >
      </div>
    </Modal>
    <!-- 查看 -->
    <Modal
      class="modal1"
      :mask-closable="false"
      v-model="viewInfo.show"
      title="查看"
    >
      <div class="viwe_title">{{ viewInfo.wname }}</div>
      <Form v-if="viewInfo.show" :label-width="80">
        <FormItem label="壁纸效果">
          <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>
        </FormItem>
        <FormItem label="适配类型">
          <div
            class="device_brand"
            v-for="brandItem in viewInfo.deviceList"
            :key="brandItem.dgroupid"
          >
            <div class="device_brand_header">
              <div class="drop_icon_box" @click="toCloseDeviceBrand(brandItem)">
                <Icon
                  :class="[
                    'drop_icon',
                    brandItem.close ? 'arrow_dropdown' : ''
                  ]"
                  type="md-arrow-dropdown"
                  :size="20"
                />
              </div>
              <Checkbox
                :disabled="true"
                :indeterminate="getIndeterminate(brandItem, viewInfo.deviceids)"
                :value="getCheckedAllValue(brandItem, viewInfo.deviceids)"
                >{{ brandItem.dgname }}</Checkbox
              >
            </div>
            <div class="device_brand_main" v-if="!brandItem.close">
              <Checkbox
                :disabled="true"
                v-for="deviceItem in brandItem.devices"
                :key="deviceItem.deviceid"
                :value="viewInfo.deviceids.includes(deviceItem.deviceid)"
                >{{ deviceItem.deviceModel }}</Checkbox
              >
            </div>
          </div>
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: center">
        <Button @click="viewInfo.show = false">关闭</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import axios from "axios";
import {
  wallpaper_list,
  wallpaper_add,
  wallpaper_edit,
  wallpaper_detail,
  wallpaper_delete
} from "@/api/setting";
import { device_list } from "@/api/appgroup";
export default {
  data() {
    return {
      userInfo: {},
      searchForm: {
        name: "",
        page: 1,
        size: 10,
        list: [],
        total: 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: "hpathSlot",
          align: "center"
        },
        {
          title: "竖屏壁纸",
          slot: "vpathSlot",
          align: "center"
        },
        {
          title: "壁纸名称",
          key: "wname",
          align: "center"
        },
        {
          title: "操作人",
          key: "updatename",
          align: "center"
        },
        {
          title: "操作时间",
          key: "updatetime",
          width: 190,
          align: "center"
        },
        {
          title: "操作",
          slot: "actionSlot",
          width: 180,
          align: "center"
        }
      ],
      // 新建/编辑
      wallpaperInfo: {
        show: false,
        wallpaperid: null,
        rversion: null,
        wname: "",
        hpath: "",
        hLoading: false,
        vpath: "",
        vLoading: false,
        // 2区域3学校
        wlevel: 3,
        // 对应的区域/学校ID
        objectid: "",
        deviceids: [],
        deviceList: []
      },
      // 查看
      viewInfo: {
        show: false,
        wname: "",
        hpath: "",
        vpath: "",
        deviceids: [],
        deviceList: []
      },
      rules: {
        wname: [
          {
            required: true,
            message: "请输入名称",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.userInfo = JSON.parse(
      localStorage.getItem("xh_control_userInfo")
    ).content;
    this.searchList();
  },
  methods: {
    // 搜索
    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() {
      console.warn("---注意替换regionid--schoolid-->wallpaper_list");
      wallpaper_list({
        page: this.searchForm.page,
        size: this.searchForm.size,
        name: this.searchForm.name,
        regionid: 11,
        schoolid: 4
      }).then((data) => {
        if (data.code === 0) {
          this.searchForm.list = data.obj.data;
          this.searchForm.total = data.obj.total;
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    // 新建
    toAdd() {
      console.warn("---objectid---->", 4);
      this.wallpaperInfo = {
        show: true,
        wallpaperid: null,
        rversion: null,
        wname: "",
        hpath: "",
        hLoading: false,
        vpath: "",
        vLoading: false,
        // 2区域3学校
        wlevel: 3,
        // 对应的区域/学校ID
        objectid: 4,
        deviceids: [],
        deviceList: []
      };
      this.getDeviceList().then((list) => {
        this.wallpaperInfo.deviceList = list;
      });
    },
    // 获取设备列表
    getDeviceList() {
      return new Promise((resolve) => {
        device_list({}).then((data) => {
          if (data.code === 0) {
            resolve(data.obj || []);
          } else {
            resolve([]);
            this.$Message.error(data.msg);
          }
        });
      });
    },
    upLoadHWallpaper(file) {
      let size = file.size / 1024 / 1024;
      let str = file.name.split(".");
      let suffix = str[str.length - 1];
      suffix = suffix.toLowerCase();
      if (
        suffix !== "png" &&
        suffix !== "jpeg" &&
        suffix !== "jpg" &&
        suffix !== "gif"
      ) {
        this.$Message.warning("请上传png、jpeg、jpg、gif类型的图片");
        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");
      this.wallpaperInfo.hLoading = true;
      axios
        .post(this.$api.baseImageUrl + "up/upfile", formData, {
          timeout: 1000 * this.$api.axiosFileTimeout
        })
        .then((res) => {
          this.wallpaperInfo.hLoading = false;
          if (res.data.code === 0) {
            this.wallpaperInfo.hpath = res.data.obj;
          } else {
            this.$Message.error(res.data.msg);
          }
        })
        .catch(() => {
          this.wallpaperInfo.hLoading = false;
          this.$Message.error("横屏壁纸上传失败");
        });
    },
    upLoadVWallpaper(file) {
      let size = file.size / 1024 / 1024;
      let str = file.name.split(".");
      let suffix = str[str.length - 1];
      suffix = suffix.toLowerCase();
      if (
        suffix !== "png" &&
        suffix !== "jpeg" &&
        suffix !== "jpg" &&
        suffix !== "gif"
      ) {
        this.$Message.warning("请上传png、jpeg、jpg、gif类型的图片");
        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");
      this.wallpaperInfo.vLoading = true;
      axios
        .post(this.$api.baseImageUrl + "up/upfile", formData, {
          timeout: 1000 * this.$api.axiosFileTimeout
        })
        .then((res) => {
          this.wallpaperInfo.vLoading = false;
          if (res.data.code === 0) {
            this.wallpaperInfo.vpath = res.data.obj;
          } else {
            this.$Message.error(res.data.msg);
          }
        })
        .catch(() => {
          this.wallpaperInfo.vLoading = false;
          this.$Message.error("竖屏壁纸上传失败");
        });
    },
    // 隐藏品牌下所有类型
    toCloseDeviceBrand(brandItem) {
      this.$set(brandItem, "close", !brandItem.close);
    },
    // 获取样式控制状态
    getIndeterminate(brandItem, deviceids) {
      let selectList = [];
      brandItem.devices.forEach((deviceItem) => {
        if (deviceids.includes(deviceItem.deviceid)) {
          selectList.push(deviceItem.deviceid);
        }
      });
      return (
        selectList.length > 0 && selectList.length !== brandItem.devices.length
      );
    },
    // 获取品牌全选状态
    getCheckedAllValue(brandItem, deviceids) {
      let selectAll = true;
      for (const deviceItem of brandItem.devices) {
        if (!deviceids.includes(deviceItem.deviceid)) {
          return false;
        }
      }
      return selectAll && brandItem.devices.length > 0;
    },
    // 设备品牌全选变化
    deviceBrandCheckedAll(brandItem, oldCheckAll) {
      if (brandItem.devices.length === 0) {
        return;
      }
      brandItem.devices.forEach((deviceItem) => {
        this.wallpaperInfo.deviceids = this.wallpaperInfo.deviceids.filter(
          (id) => id !== deviceItem.deviceid
        );
        if (!oldCheckAll) {
          this.wallpaperInfo.deviceids.push(deviceItem.deviceid);
        }
      });
    },
    // 品牌类型选中改变
    deviceModelCheck(deviceItem) {
      if (this.wallpaperInfo.deviceids.includes(deviceItem.deviceid)) {
        this.wallpaperInfo.deviceids = this.wallpaperInfo.deviceids.filter(
          (id) => id !== deviceItem.deviceid
        );
      } else {
        this.wallpaperInfo.deviceids.push(deviceItem.deviceid);
      }
    },
    // 保存新建
    saveAddInfo() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          if (!(this.wallpaperInfo.hpath || this.wallpaperInfo.vpath)) {
            this.$Message.error("请上传壁纸");
            return;
          }
          this.wallpaperInfo.show = false;
          let form = {
            wname: this.wallpaperInfo.wname,
            hpath: this.wallpaperInfo.hpath,
            vpath: this.wallpaperInfo.vpath,
            wlevel: this.wallpaperInfo.wlevel,
            objectid: this.wallpaperInfo.objectid,
            deviceids: this.wallpaperInfo.deviceids
          };
          if (this.wallpaperInfo.wallpaperid && this.wallpaperInfo.rversion) {
            form.wallpaperid = this.wallpaperInfo.wallpaperid;
            form.rversion = this.wallpaperInfo.rversion;
          }
          let api =
            this.wallpaperInfo.wallpaperid && this.wallpaperInfo.rversion
              ? wallpaper_edit
              : wallpaper_add;
          api(form).then((data) => {
            if (data.code === 0) {
              this.searchList();
              this.$Message.success(data.msg);
            } else {
              this.$Message.error(data.msg);
            }
          });
        }
      });
    },
    // 查看
    toView(row) {
      this.viewInfo = {
        show: true,
        wname: row.wname,
        hpath: row.hpath,
        vpath: row.vpath,
        deviceids: [],
        deviceList: []
      };
      this.getWallpaperDetail(row.wallpaperid).then((data) => {
        if (data) {
          let _deviceids = [];
          data.devices.forEach((brandItem) => {
            brandItem.devices.forEach((deviceItem) => {
              _deviceids.push(deviceItem.deviceid);
            });
          });
          this.viewInfo.deviceids = _deviceids;
        }
      });
      this.getDeviceList().then((list) => {
        this.viewInfo.deviceList = list;
      });
    },
    // 编辑
    toEdit(row) {
      this.wallpaperInfo = {
        show: true,
        wallpaperid: row.wallpaperid,
        rversion: row.rversion,
        wname: row.wname,
        hpath: row.hpath,
        hLoading: false,
        vpath: row.vpath,
        vLoading: false,
        // 2区域3学校
        wlevel: row.wlevel,
        // 对应的区域/学校ID
        objectid: row.objectid,
        deviceids: [],
        deviceList: []
      };
      this.getWallpaperDetail(row.wallpaperid).then((data) => {
        if (data) {
          let _deviceids = [];
          data.devices.forEach((brandItem) => {
            brandItem.devices.forEach((deviceItem) => {
              _deviceids.push(deviceItem.deviceid);
            });
          });
          this.wallpaperInfo.deviceids = _deviceids;
        }
      });
      this.getDeviceList().then((list) => {
        this.wallpaperInfo.deviceList = list;
      });
    },
    getWallpaperDetail(wallpaperid) {
      return new Promise((resolve) => {
        wallpaper_detail({ wallpaperid }).then((data) => {
          if (data.code === 0) {
            resolve(data.obj);
          } else {
            resolve();
            this.$Message.error(data.msg);
          }
        });
      });
    },
    // 删除
    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;
}
.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;
  }
}
.device_brand {
  /deep/.ivu-checkbox-wrapper {
    font-size: 16px;
  }
  .device_brand_header {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    .drop_icon_box {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      margin-right: 4px;
      height: 32px;
      cursor: pointer;
      .drop_icon {
        transition: all 0.1s ease-in-out;
        &.arrow_dropdown {
          transform: rotate(-90deg);
        }
      }
    }
  }
  .device_brand_main {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    padding-left: 24px;
  }
}
.viwe_title {
  margin-bottom: 16px;
  font-size: 18px;
  font-weight: bold;
  text-align: center;
}
.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%;
      }
    }
  }
}
</style>
