<template>
  <div class="main_root">
    <div class="search_header">
      <div class="search_left">
        <Select
          :transfer="true"
          v-model="searchForm.appgroupid"
          style="width: 120px; margin: 0 10px"
          placeholder="请选择分组"
        >
          <template v-if="group_list.length > 0">
            <Option
              v-for="item in group_list"
              :value="item.appgroupid"
              :key="item.appgroupid"
              >{{ item.appgroupName }}</Option
            >
          </template>
        </Select>
        <Input
          v-model="searchForm.appName"
          placeholder="请输入名称"
          search
          @on-search="searchList()"
          style="width: 150px"
        />
      </div>
      <Button type="primary" class="primary_btn" @click="toAdd()">新建</Button>
    </div>
    <div class="table_wrap">
      <Table :columns="columns" :data="searchForm.list">
        <template slot-scope="{ row }" slot="appName">
          <div class="appName">
            <div class="app_logo">
              <img :src="$api.showImageUrl + row.appIcon" />
            </div>
            <div class="app_comm">
              <div>{{ row.appName }}</div>
              <span>版本: {{ row.versionName }}</span>
              <div>授权型号: {{ row.devicenum }}个</div>
            </div>
          </div>
        </template>
        <template slot-scope="{ row }" slot="appType">
          <div>{{ row.appType === 1 ? "推荐应用" : "必装应用" }}</div>
        </template>
        <template slot-scope="{ row }" slot="enable">
          <i-switch
            size="large"
            v-model="row.enable"
            :true-value="1"
            :false-value="2"
            @on-change="enabledChange(row)"
          >
            <span slot="open">启用</span>
            <span slot="close">禁用</span>
          </i-switch>
        </template>
        <template slot-scope="{ row }" slot="whited">
          <div class="action_list">
            <div class="action_success">
              {{ row.whited === 1 ? "是" : "否" }}
            </div>
          </div>
        </template>
        <template slot-scope="{ row }" slot="trusted">
          <div class="action_list">
            <div class="action_del">
              {{ row.trusted === 1 ? "是" : "否" }}
            </div>
          </div>
        </template>
        <template slot-scope="{ row }" slot="showico">
          <div class="action_list">
            <div class="action_success">
              {{ row.showico === 1 ? "是" : "否" }}
            </div>
          </div>
        </template>

        <template slot-scope="{ row }" slot="countSlot">
          <div class="action_list">
            <div @click="countSlot(row, 1)">下载</div>
            <div @click="countSlot(row, 2)">安装统计</div>
          </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 application"
      :mask-closable="false"
      v-model="wallpaperInfo.show"
      :title="wallpaperInfo.appid ? '编辑' : '新建'"
    >
      <Form
        ref="addForm"
        :model="wallpaperInfo"
        :rules="rules"
        :label-width="130"
        inline
      >
        <FormItem label="名称" prop="appName" style="width: 100%">
          <Input
            v-model="wallpaperInfo.appName"
            placeholder="请输入名称"
          ></Input>
        </FormItem>
        <FormItem label="分组" style="width: 100%" class="require">
          <Select
            v-model="wallpaperInfo.appgroupid"
            placeholder="请选择分组"
            style="width: 300px"
            @on-change="groupChange()"
          >
            <template v-if="group_list.length > 0">
              <Option
                v-for="item in group_list"
                :value="item.appgroupid"
                :key="item.appgroupid"
                >{{ item.appgroupName }}</Option
              >
            </template>
          </Select>
        </FormItem>
        <FormItem label="状态" style="width: 300px">
          <RadioGroup v-model="wallpaperInfo.appState">
            <Radio :label="1">启用</Radio>
            <Radio :label="2">禁用</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="应用属性">
          <RadioGroup v-model="wallpaperInfo.appType">
            <Radio :label="1">推荐应用</Radio>
            <Radio :label="2">必装应用</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="强制安装" style="width: 100%">
          <div class="comm">
            <RadioGroup v-model="wallpaperInfo.forced">
              <Radio :label="1">是</Radio>
              <Radio :label="0">否</Radio>
            </RadioGroup>
            <span>用户进入安全桌面，该应用将被强制安装。</span>
          </div>
        </FormItem>
        <FormItem label="网址白名单例外" style="width: 100%">
          <div class="comm">
            <RadioGroup v-model="wallpaperInfo.whited">
              <Radio :label="1">是</Radio>
              <Radio :label="0">否</Radio>
            </RadioGroup>
            <span>选择白名单例外则该应用访问网络不受网址白名单限制。</span>
          </div>
        </FormItem>
        <FormItem label="可信任" style="width: 100%">
          <div class="comm">
            <RadioGroup v-model="wallpaperInfo.trusted">
              <Radio :label="1">是</Radio>
              <Radio :label="0">否</Radio>
            </RadioGroup>
            <span
              >选择可信任时，应用申请权限不需要用户确认，防止用户取消。</span
            >
          </div>
        </FormItem>
        <FormItem label="隐藏图标" style="width: 100%">
          <div class="comm">
            <RadioGroup v-model="wallpaperInfo.showico">
              <Radio :label="1">是</Radio>
              <Radio :label="0">否</Radio>
            </RadioGroup>
            <span>隐藏图标时，设备安装应用后，桌面不显示应用图标。</span>
          </div>
        </FormItem>
        <FormItem label="允许清空缓存" style="width: 100%">
          <div class="comm">
            <RadioGroup v-model="wallpaperInfo.cached">
              <Radio :label="1">是</Radio>
              <Radio :label="0">否</Radio>
            </RadioGroup>
            <span>选择是时，设备上允许清除该应用对应的缓存。</span>
          </div>
        </FormItem>
        <FormItem label="添加到已有策略" style="width: 100%">
          <div class="comm">
            <RadioGroup v-model="wallpaperInfo.strategy">
              <Radio :label="1">是</Radio>
              <Radio :label="0">否</Radio>
            </RadioGroup>
            <span
              >选择添加到已有策略，则当前应用会被添加到其授权的且不存在相同包名应用的学校策略。</span
            >
          </div>
        </FormItem>
        <FormItem label="适配设备" style="width: 100%" class="require">
          <div v-for="item in device_list" :key="item.dgroupid">
            <CheckboxDevice
              @CheckboxDevice="CheckboxDevice"
              :dgroupid="item.dgroupid"
              ref="checkbevice"
              :module="item"
            ></CheckboxDevice>
          </div>
        </FormItem>
        <FormItem label="应用上传" class="require" style="width: 400px">
          <div class="upload_box">
            <uploader
              ref="uploader"
              :options="options"
              :autoStart="true"
              :file-status-text="statusText"
              @file-added="onFileAdded"
              @file-progress="onFileProgress"
              @file-success="onFileSuccess"
              @file-error="onFileError"
            >
              <uploader-unsupport></uploader-unsupport>
              <uploader-btn
                id="global_uploader_btn"
                :attrs="attrs"
                ref="uploadBtn"
              >
                <div class="primary_btn">上传应用</div>
              </uploader-btn>
            </uploader>
          </div>
          <div class="upProgress" v-if="file_list.length > 0">
            <div v-for="file in file_list" key="file1">
              <div class="file_name" :title="wallpaperInfo.appPackage">
                <div class="show_name">
                  {{ wallpaperInfo.appPackage }}
                </div>
              </div>
              <Progress
                hide-info
                :stroke-width="8"
                :percent="getUploadProgress(file)"
                status="active"
              />
            </div>
          </div>
        </FormItem>
        <FormItem label="应用图标" class="require">
          <div class="logo">
            <Upload
              action
              :show-upload-list="false"
              :before-upload="
                (file) => {
                  upLoadUserpic(file, 1);
                  return false;
                }
              "
              accept=".png,.jpeg,.jpg"
            >
              <Button type="primary" class="primary_btn">上传图标</Button>
            </Upload>
            <span>支持图片格式：jpg、jgeg、png</span>
          </div>
          <div class="app_img" style="border-radius: 20px">
            <img
              v-if="wallpaperInfo.appIcon"
              :src="$api.showImageUrl + wallpaperInfo.appIcon"
            />
          </div>
        </FormItem>
        <FormItem label="应用截图" style="width: 100%">
          <div class="logo">
            <Upload
              action
              :show-upload-list="false"
              :before-upload="
                (file) => {
                  upLoadUserpic(file, 2);
                  return false;
                }
              "
              accept=".png,.jpeg,.jpg"
            >
              <Button type="primary" class="primary_btn">上传截图</Button>
            </Upload>
            <span>支持图片格式：jpg、jgeg、png</span>
          </div>
          <div class="img_list">
            <div
              class="app_img"
              v-for="(img, idx) in wallpaperInfo.appImg"
              :key="idx"
            >
              <img :src="$api.showImageUrl + img" />
              <img
                @click="delAppImg(idx)"
                class="del"
                src="../../../assets/img/guanbi_red.png"
              />
            </div>
          </div>
        </FormItem>
        <FormItem
          label="版本名称"
          prop="versionName"
          style="width: calc(50% - 10px)"
        >
          <Input
            v-model="wallpaperInfo.versionName"
            placeholder="请输入版本名称"
          ></Input>
        </FormItem>
        <FormItem
          label="版本号码"
          class="require"
          style="width: calc(50% - 10px)"
        >
          <Input
            v-model="wallpaperInfo.versionNum"
            placeholder="请输入版本号码"
          ></Input>
        </FormItem>
        <FormItem
          label="应用大小"
          class="require"
          style="width: calc(50% - 10px)"
        >
          <Input
            v-model="wallpaperInfo.appSize"
            placeholder="请输入应用大小"
          ></Input>
        </FormItem>
        <FormItem label="开发者" style="width: calc(50% - 10px)">
          <Input
            v-model="wallpaperInfo.appDeveloper"
            placeholder="请输入开发者"
          ></Input>
        </FormItem>
        <FormItem label="应用包名" style="width: 100%">
          <Input
            v-model="wallpaperInfo.appPackage"
            placeholder="请输入应用包名"
          ></Input>
        </FormItem>
        <FormItem label="应用简介" style="width: 100%">
          <Input
            v-model="wallpaperInfo.appAbbr"
            type="textarea"
            :maxlength="255"
            :rows="4"
            placeholder="请输入应用简介"
          ></Input>
          <div class="appcomm">
            应用简介不能超过255个字符<span class="red">{{
              wallpaperInfo.appAbbr.length
            }}</span
            >/255
          </div>
        </FormItem>
        <FormItem label="更新" style="width: 100%">
          <Input
            v-model="wallpaperInfo.appRenew"
            type="textarea"
            :rows="4"
            :maxlength="1000"
            placeholder="请输入更新描述"
          ></Input>
          <div class="appcomm">
            更新描述不能超过1000个字符<span class="red">{{
              wallpaperInfo.appRenew.length
            }}</span
            >/1000
          </div>
        </FormItem>
        <FormItem label="选择学校" style="width: 100%" class="require">
          <RadioGroup v-model="wallpaperInfo.targetSchool">
            <Radio :label="1">所有学校</Radio>
            <Radio :label="2">自定义学校</Radio>
          </RadioGroup>
          <div class="targetSchool" v-if="wallpaperInfo.targetSchool === 2">
            <div class="allSchool">
              <Input
                v-model="wallpaperInfo.schoolname"
                placeholder="请输入关键字"
                search
                @on-search="getSchool"
              ></Input>
              <div class="school_list">
                <Tree
                  @on-check-change="getSelectedNodes"
                  :data="school_list"
                  show-checkbox
                ></Tree>
              </div>
            </div>
            <div class="selectSchool">
              <div class="school_num">
                已选<span class="num">{{ select_schools.length }}</span
                >所学校
              </div>
              <div class="school_list">
                <span
                  class="school_item"
                  v-for="(item, index) in this.select_schools"
                  :key="item.schoolid"
                >
                  <span class="title" :title="item.title">{{
                    item.title
                  }}</span>
                  <img
                    @click="delSchool(item)"
                    class="del"
                    src="../../../assets/img/guanbi_red.png"
                  />
                </span>
              </div>
            </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="view_title">河南星火燎原软件科技有限公司</div>
      <Table
        style="border: 1px solid #e8eaec; border-bottom: none"
        :columns="viewInfo.columns"
        :data="viewInfo.list"
      >
      </Table>
      <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 { date_format, uuid } from "@/utils";
import axios from "axios";
import {
  app_add,
  app_delete,
  app_detail,
  app_edit,
  app_edit_enable,
  app_edit_unenable,
  app_list,
  appgroup_list,
  device_list
} from "@/api/appgroup";
import CheckboxDevice from "@/components/Checkbox/CheckboxDevice";
import { ACCEPT_CONFIG, CHUNK_SIZE, CONFIG_SUFFIX } from "@/utils/fileConfig";
import { region_list_rs } from "@/api/region";
export default {
  components: {
    CheckboxDevice
  },
  data() {
    return {
      date_format,
      file_list: [],
      upTimer: null,
      options: {
        singleFile: false, //批量上传
        target: this.$api.baseImageUrl + "chunk/up", //地址
        chunkSize: CHUNK_SIZE.getSize(), //分块大小
        fileParameterName: "file", //上传文件名，
        maxChunkRetries: 3, //最大自动失败重试上传次数
        testChunks: false //是否开启服务器分片校验
      },
      attrs: {
        accept: ACCEPT_CONFIG.getApp()
      },
      statusText: {
        success: "上传成功",
        error: "上传失败",
        uploading: "上传中",
        paused: "等待中", //暂停中
        waiting: "等待中"
      },
      showLoading: false,
      searchForm: {
        appName: "",
        page: 1,
        size: 10,
        list: [],
        total: 0
      },
      // 新建/编辑
      wallpaperInfo: {
        show: false,
        appid: null,
        appName: "",
        appgroupid: "",
        appState: 1,
        appType: 1,
        forced: 1,
        whited: 1,
        trusted: 1,
        showico: 1,
        cached: 1,
        strategy: 1,
        apkPath: "",
        appIcon: "",
        appImg: [],
        versionName: "",
        versionNum: "",
        appSize: "",
        appDeveloper: "",
        appPackage: "",
        appAbbr: "",
        appRenew: "",
        targetSchool: 2,
        deviceids: [],
        schoolids: []
      },
      // 查看
      viewInfo: {
        show: false,
        areaname: "",
        list: [],
        columns: [
          {
            title: "序号",
            type: "index",
            width: 70,
            align: "center"
          },
          {
            title: "名称",
            key: "admin",
            align: "center"
          },
          {
            title: "账号",
            key: "loginname",
            align: "center"
          },
          {
            title: "手机号码",
            key: "phone",
            align: "center"
          }
        ]
      },
      rules: {
        appName: [
          {
            required: true,
            message: "请输入名称",
            trigger: "blur"
          }
        ],
        appgroupid: [
          {
            required: true,
            message: "请选择分组",
            trigger: "blur"
          }
        ],
        versionName: [
          {
            required: true,
            message: "请输入名称",
            trigger: "blur"
          }
        ],
        versionNum: [
          {
            required: true,
            message: "请输入名称",
            trigger: "blur"
          }
        ],
        appSize: [
          {
            required: true,
            message: "请输入名称",
            trigger: "blur"
          }
        ]
      },
      group_list: [],
      device_list: [],
      curRegion: [], //当前区域所有
      school_list: [], //当前区域学校 搜索
      select_schools: [],
      deviceids: {}, //设备类型
      userInfo: {},
      columns: [
        {
          title: "序号",
          align: "center",
          width: 70,
          render: (h, params) => {
            return h(
              "span",
              params.index +
                (this.searchForm.page - 1) * this.searchForm.size +
                1
            );
          }
        },
        {
          title: "应用",
          slot: "appName",
          align: "center"
        },
        {
          title: "分组",
          key: "appgroupName",
          align: "center",
          width: 120
        },
        {
          title: "属性应用",
          slot: "appType",
          align: "center",
          width: 100
        },
        {
          title: "状态",
          slot: "enable",
          width: 100,
          align: "center"
        },
        {
          title: "网址白名单例外",
          slot: "whited",
          align: "center",
          width: 140
        },
        {
          title: "可信任",
          slot: "trusted",
          align: "center",
          width: 80
        },
        {
          title: "隐藏图标",
          slot: "showico",
          align: "center",
          width: 100
        },
        {
          title: "操作时间",
          key: "updatetime",
          align: "center",
          width: 180
        },
        {
          title: "统计",
          slot: "countSlot",
          align: "center",
          width: 160
        },
        {
          title: "操作",
          slot: "actionSlot",
          width: 180,
          align: "center"
        }
      ]
    };
  },
  created() {
    this.userInfo = JSON.parse(
      localStorage.getItem("xh_control_userInfo")
    ).content;
    this.init();
    this.searchList();
  },
  methods: {
    enabledChange(row) {
      let api = row.enable === 1 ? app_edit_enable : app_edit_unenable;
      api({
        appid: row.appid,
        rversion: row.rversion
      }).then((data) => {
        this.searchList();
        if (data.code === 0) {
          this.$Message.success(data.msg);
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    countSlot(row, type) {
      if (type === 1) {
        //下载
      } else if (type === 2) {
        //安装统计
      }
    },
    //删除截图
    delAppImg(index) {
      this.wallpaperInfo.appImg.splice(index, 1);
    },
    delSchool(item) {
      this.select_schools = this.select_schools.filter(
        (v) => v.schoolid != item.schoolid
      );
      //取消选择
      this.getSelectSchool(this.school_list[0], item.schoolid, 0);
    },
    //选中区域学校
    getSelectedNodes(data) {
      this.select_schools = data.filter((v) => v.schoolid);
      console.log(this.select_schools);
    },
    getUploadProgress(file) {
      let progress = file.progress();
      if (!progress) {
        progress = 0;
      }
      return progress * 100;
    },
    async onFileAdded(file) {
      let that = this;
      let { name } = file.file;
      file.uniqueIdentifier = uuid();
      file.suffix = that.getFileSuffix(name);
      let deviceIndex = that.getArrIndex(file.suffix, CONFIG_SUFFIX.getApp());
      if (deviceIndex == -1) {
        this.$Message.error("文件格式不正确");
        return false;
      }
      let fname = file.name;
      let resourcename = fname.substring(0, fname.lastIndexOf("."));
      file.resourcename = resourcename;
      this.file_list = [file];
    },
    //查找下标
    getArrIndex(obj, arr) {
      for (let h = 0; h < arr.length; h++) {
        if (obj == arr[h]) {
          return h;
        }
      }
      return -1;
    },
    getFileSuffix(fileName) {
      let dotIndex = fileName.lastIndexOf(".");
      let fileType = fileName.slice(dotIndex + 1);
      return fileType.toLowerCase();
    },
    onFileProgress(rootFile, file) {
      file.progress();
      this.showLiading = true;
    },
    onFileSuccess(rootFile, file, response) {
      let that = this;
      let res = JSON.parse(response);
      // 服务器自定义的错误（即虽返回200，但是是错误的情况），这种错误是Uploader无法拦截的
      if (res.code === 0) {
        //合并
        let url = this.$api.baseImageUrl + "chunk/merge_app";
        let formData = new FormData();
        formData.append("identifier", file.uniqueIdentifier);
        formData.append("filename", `${file.resourcename}.${file.suffix}`);
        formData.append("savefolder", "app");
        // 进行post 请求
        axios({
          method: "post",
          timeout: 1000 * window._config.axiosFileTimeout,
          url,
          data: formData,
          headers: {
            "Content-Type": "application/x-www-form-urlencoded"
          }
        })
          .then((response) => {
            let res = response.data;
            if (res.code === 0) {
              that.wallpaperInfo.apkPath = res.obj.apkPath;
              that.wallpaperInfo.appIcon = res.obj.appIcon;
              that.wallpaperInfo.appPackage = res.obj.appPackage;
              that.wallpaperInfo.appSize = res.obj.appSize;
              that.wallpaperInfo.versionName = res.obj.versionName;
              that.wallpaperInfo.versionNum = res.obj.versionNum;
              that.showLiading = false;
            } else {
              that.$Message.error(`${file.name} ${res.msg}`);
              that.showLiading = false;
            }
          })
          .catch(() => {
            that.$Message.error("上传失败");
            that.showLiading = false;
          });
      } else {
        that.$Message.error(`${file.name} ${res.msg}`);
        that.showLiading = false;
      }
    },
    onFileError(rootFile, file, response) {
      let res = JSON.parse(response);
      this.$Message.error(`${file.name} ${res.msg}`);
      this.showLiading = false;
    },
    CheckboxDevice(dgroupid, val) {
      this.deviceids[dgroupid] = val;
      console.log(this.deviceids);
    },
    init() {
      //获取分组列表
      appgroup_list({
        page: 1,
        size: 100,
        appgroupName: ""
      }).then((res) => {
        if (res.code === 0) {
          this.group_list = res.obj.data;
        } else {
          this.$Message.error(res.msg);
        }
      });
      //获取分组下设备
      device_list({}).then((res) => {
        if (res.code === 0) {
          this.device_list = res.obj;
        } else {
          this.$Message.error(res.msg);
        }
      });

      //获取区域学校
      region_list_rs({ regionid: this.userInfo.regionid }).then((res) => {
        if (res.code === 0) {
          this.getHandleData(res.obj[0]);
          this.curRegion = res.obj;
        } else {
          this.$Message.error(res.msg);
        }
      });
    },
    getHandleData(node) {
      node.title = node.regionName;
      node.expand = true;
      if (node.children && node.children.length > 0) {
        for (let child of node.children) {
          this.getHandleData(child);
        }
      }
    },
    getSchool() {
      //wallpaperInfo.schoolname
      //获取区域学校
      region_list_rs({
        regionid: this.userInfo.regionid,
        regionName: this.wallpaperInfo.schoolname
      }).then((res) => {
        if (res.code === 0) {
          this.getHandleData(res.obj[0]);
          this.school_list = res.obj;
          console.log(this.school_list);
        } else {
          this.$Message.error(res.msg);
        }
      });
    },
    groupChange() {},
    upLoadUserpic(file, type) {
      //type 1图标/2截图
      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;
      }
      if (type === 2) {
        if (this.wallpaperInfo.appImg.length > 5) {
          this.$Message.warning("最多上传五张截图！");
          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) {
            if (type === 1) {
              //图标
              this.wallpaperInfo.appIcon = res.data.obj;
            } else {
              //截图
              this.wallpaperInfo.appImg.push(res.data.obj);
            }
            this.$Message.success(res.data.msg);
          } else {
            this.$Message.error(res.data.msg);
          }
        })
        .catch(() => {
          this.showLoading = false;
          this.$Message.error("图片上传失败");
        });
    },
    // 区域选择改变
    searchAreaChange() {},
    // 搜索
    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() {
      app_list({
        page: this.searchForm.page,
        size: this.searchForm.size,
        appName: this.searchForm.appName
      }).then((res) => {
        if (res.code === 0) {
          this.searchForm.list = res.obj.data;
          this.searchForm.total = res.obj.total;
          console.log(this.searchForm.list);
        } else {
          this.$Message.error(res.msg);
        }
      });
    },
    // 新建
    toAdd() {
      this.$refs.addForm.resetFields();
      this.wallpaperInfo = {
        show: true,
        appid: null,
        appName: "",
        appgroupid: "",
        appState: 1,
        appType: 1,
        forced: 1,
        whited: 1,
        trusted: 1,
        showico: 1,
        cached: 1,
        strategy: 1,
        apkPath: "",
        appIcon: "",
        appImg: [],
        versionName: "",
        versionNum: "",
        appSize: "",
        appDeveloper: "",
        appPackage: "",
        appAbbr: "",
        appRenew: "",
        targetSchool: 1,
        deviceids: [],
        schoolids: []
      };
      this.school_list = JSON.parse(JSON.stringify(this.curRegion));
    },
    // 保存新建
    saveAddInfo() {
      console.log(this.wallpaperInfo);
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          if (!this.wallpaperInfo.appgroupid) {
            this.$Message.error("请选择分组");
            return;
          }
          //获取设备
          let deviceids = [];
          for (let key in this.deviceids) {
            for (let deviceid of this.deviceids[key]) {
              deviceids.push(deviceid);
            }
          }
          if (!this.wallpaperInfo.apkPath) {
            this.$Message.error("请上传应用!");
            return;
          }
          if (!this.wallpaperInfo.appIcon) {
            this.$Message.error("请上传图标!");
            return;
          }
          if (!this.wallpaperInfo.versionNum) {
            this.$Message.error("请输入版本号码");
            return;
          }
          if (!this.wallpaperInfo.appSize) {
            this.$Message.error("请输入应用大小");
            return;
          }
          if (this.wallpaperInfo.targetSchool === 1) {
            //获取全部学校
            this.getSelectSchool(this.curRegion[0], null);
          } else {
            //获取选中学校
            for (let school of this.select_schools) {
              this.wallpaperInfo.schoolids.push(school.schoolid);
            }
          }
          if (this.wallpaperInfo.schoolids.length === 0) {
            this.$Message.error("请选择学校!");
            return;
          }
          let appImg = this.wallpaperInfo.appImg.join(";");
          let form = {
            appName: this.wallpaperInfo.appName,
            appState: this.wallpaperInfo.appState,
            appType: this.wallpaperInfo.appType,
            forced: this.wallpaperInfo.forced,
            whited: this.wallpaperInfo.whited,
            trusted: this.wallpaperInfo.trusted,
            showico: this.wallpaperInfo.showico,
            strategy: this.wallpaperInfo.strategy,
            cached: this.wallpaperInfo.cached,
            appgroupid: this.wallpaperInfo.appgroupid,
            apkPath: this.wallpaperInfo.apkPath,
            appIcon: this.wallpaperInfo.appIcon,
            appImg, //应用截图：多张图片用分号分割
            versionName: this.wallpaperInfo.versionName,
            versionNum: this.wallpaperInfo.versionNum,
            appSize: this.wallpaperInfo.appSize,
            appDeveloper: this.wallpaperInfo.appDeveloper,
            appPackage: this.wallpaperInfo.appPackage,
            appAbbr: this.wallpaperInfo.appAbbr,
            appRenew: this.wallpaperInfo.appRenew,
            targetSchool: this.wallpaperInfo.targetSchool,
            deviceids,
            schoolids: this.wallpaperInfo.schoolids
          };
          console.log(form);
          let api = this.wallpaperInfo.appid ? app_edit : app_add;
          api(form).then((res) => {
            if (res.code === 0) {
              this.wallpaperInfo.show = false;
              console.log(res.obj);
              this.$Message.success(res.msg);
              this.searchList();
            } else {
              this.$Message.error(res.msg);
            }
          });
        }
      });
    },
    getSelectSchool(node, schoolid, type) {
      if (schoolid) {
        //删除
        if (node.schoolid && node.schoolid === schoolid) {
          let checked = type ? true : false;
          this.$set(node, "checked", checked);
        }
      } else {
        //保存
        if (node.schoolid) {
          this.wallpaperInfo.schoolids.push(node.schoolid);
        }
      }
      if (node.children && node.children.length > 0) {
        for (let child of node.children) {
          this.getSelectSchool(child, schoolid, type);
        }
      }
    },
    //进入
    toGo(row) {},
    // 查看
    toView() {
      this.viewInfo.show = true;
      this.viewInfo.areaname = "河南星火燎原软件科技有限公司";
      this.viewInfo.list = [
        {
          admin: "周文彦",
          loginname: "zhouwenyan@xhkjedu.com",
          phone: "15610230213"
        },
        {
          admin: "齐思宇",
          loginname: "zhouwenyan@xhkjedu.com",
          phone: "15610230213"
        }
      ];
    },
    // 编辑
    toEdit(row) {
      app_detail({ appid: row.appid }).then((res) => {
        if (res.code === 0) {
          this.school_list = JSON.parse(JSON.stringify(this.curRegion));
          this.wallpaperInfo = {
            show: true,
            appid: res.obj.appid,
            appName: res.obj.appName,
            appgroupid: res.obj.appgroupid,
            appState: res.obj.enable,
            appType: res.obj.appType,
            forced: res.obj.forced,
            whited: res.obj.whited,
            trusted: res.obj.trusted,
            showico: res.obj.showico,
            cached: res.obj.cached,
            strategy: res.obj.strategy,
            apkPath: res.obj.apkPath,
            appIcon: res.obj.appIcon,
            appImg: res.obj.appImg.split(";"),
            versionName: res.obj.versionName,
            versionNum: res.obj.versionNum,
            appSize: res.obj.appSize,
            appDeveloper: res.obj.appDeveloper,
            appPackage: res.obj.appPackage,
            appAbbr: res.obj.appAbbr,
            appRenew: res.obj.appRenew,
            targetSchool: res.obj.targetSchool,
            deviceids: [],
            schoolids: []
          };

          this.$nextTick(() => {
            //回显应用上传
            this.file_list = [
              {
                progress: () => {
                  return 1;
                }
              }
            ];
            //回显设备
            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);
                  }
                }
              }
            }

            if (this.wallpaperInfo.targetSchool === 2) {
              //回显学校
              this.select_schools = res.obj.schools.map((v) => {
                //默认选择学校
                this.getSelectSchool(this.school_list[0], v.schoolid, 1);
                v.title = v.schoolName;
                return v;
              });

              console.log(this.select_schools);
            }
          });

          console.log(res.obj);
          console.log(this.wallpaperInfo);
        } else {
          this.$Message.error(res.msg);
        }
      });
    },
    // 删除
    toDel(row) {
      this.$Modal.confirm({
        title: "提示",
        content: "您确定删除选中数据吗？",
        onOk: () => {
          app_delete({ appid: row.appid, rversion: row.rversion }).then(
            (res) => {
              if (res.code === 0) {
                this.$Message.success(res.msg);
                this.searchList();
              } else {
                this.$Message.error(res.msg);
              }
            }
          );
        },
        onCancel: () => {}
      });
    }
  }
};
</script>

<style lang="less" scoped>
.search_header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 16px 16px;
  .search_left {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .search_drop {
      margin-right: 10px;
      width: 150px;
    }
  }
}
.table_wrap {
  .appName {
    display: flex;
    margin: 16px 0;
    .app_logo {
      flex-wrap: none;
      width: 56px;
      height: 56px;
      border-radius: 20px;
      border: 1px solid #e5e5e5;
      background: #ffffff;
      padding: 10px;
      img {
        width: 38px;
        height: 38px;
        object-fit: cover;
      }
    }
    .app_comm {
      flex: none;
      width: 120px;
      margin-left: 10px;
      text-align: left;
      div {
        color: #339dff;
      }
    }
  }
}
.code_btn {
  display: inline-block;
  margin-left: 10px;
  padding: 0 10px;
  color: #339dff;
  line-height: 30px;
  border: 1px solid #339dff;
  border-radius: 6px;
  background-color: #fff;
  cursor: pointer;
  &.disabled {
    color: #c5c8ce;
    background-color: #f7f7f7;
    border-color: #dcdee2;
    cursor: not-allowed;
  }
}
.view_title {
  margin-bottom: 16px;
  font-size: 18px;
  font-weight: bold;
  text-align: center;
}
.application {
  .comm {
    display: flex;
    align-items: center;
    span {
      margin-left: 20px;
      color: #b8c2d9;
    }
  }
  .appcomm {
    height: 20px;
    line-height: 20px;
    text-align: right;
    color: #b8c2d9;
    font-size: 14px;
    .red {
      display: inline-block;
      margin: 0 4px;
      color: #f0153f;
    }
  }
  .logo {
    height: 34px;
    display: flex;
    align-items: center;
    span {
      font-size: 16px;
      margin-left: 10px;
      color: #7c8db5;
    }
  }
  .img_list {
    height: 90px;
    display: flex;
  }
  .app_img {
    margin-top: 10px;
    width: 90px;
    height: 90px;
    margin-right: 20px;
    opacity: 1;
    border: 1px solid #e5e5e5;
    background: #ffffff;
    overflow: hidden;
    position: relative;
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    .del {
      width: 20px;
      height: 20px;
      object-fit: cover;
      position: absolute;
      right: 6px;
      top: 6px;
      cursor: pointer;
    }
  }
  .targetSchool {
    width: 100%;
    height: 400px;
    border: 1px solid #ced9f2;
    border-radius: 8px;
    margin-top: 10px;
    display: flex;
    .allSchool {
      border-right: 1px solid #ced9f2;
      width: 50%;
      padding: 10px;
      .school_list {
        margin-top: 10px;
        height: calc(100% - 42px);
        overflow-y: auto;
      }
    }
    .selectSchool {
      width: 50%;
      padding: 10px;
      .school_num {
        height: 32px;
        display: flex;
        align-items: center;
        .num {
          color: #339cff;
          font-weight: bold;
          margin: 0 2px;
        }
      }
      .school_list {
        margin-top: 10px;
        height: calc(100% - 42px);
        overflow-y: auto;
        .school_item {
          display: inline-block;
          width: calc(50% - 10px);
          height: 28px;
          line-height: 28px;
          border-radius: 6px;
          font-size: 14px;
          padding: 0 30px 0 10px;
          margin-right: 10px;
          margin-bottom: 10px;
          background: #f3f4fc;
          position: relative;
          .title {
            display: inline-block;
            width: calc(100% - 10px);
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
          }
          .del {
            width: 20px;
            height: 20px;
            object-fit: cover;
            position: absolute;
            right: 10px;
            top: 4px;
            cursor: pointer;
          }
        }
      }
    }
  }
  .upload_box {
    /deep/ .uploader-btn {
      border: navajowhite;
      padding: 0;
      &:hover {
        background-color: transparent;
      }
    }
  }
  .upProgress {
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    > div {
      margin: 0 10px;
      width: 100%;
    }
  }
  .file_name {
    height: 32px;
    margin-top: 10px;
    .show_name {
      font-size: 14px;
      color: #333;
      text-align: left;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      line-height: 32px;
      cursor: pointer;
    }
  }
}

.primary_btn {
  border-radius: 8px;
  color: white;
  line-height: 35px;
  padding: 0 15px;
  height: 35px;
  font-size: 14px;
  background: linear-gradient(180deg, #30e5fc 0%, #34a4ff 100%);
  box-shadow: inset 0 1px 2px 0 #ffffffb3, inset 0 -2px 3px 0 #ffffff4d,
    0 3px 5px 0 #339dff80, inset 0 -2px 0 0 #2b89e0;
}
</style>
