<template>
  <div>
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="#">基础信息管理</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="#">设备人员管理</a>
      </el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <!--
      要resetFields起作用，必须配置:model和prop
    -->
    <el-form
      ref="queryForm"
      :model="queryModel"
      :rules="ruleValidate"
      inline
      class="demo-form-inline"
    >
      <div>
        <el-form-item label="姓名" prop="name">
          <el-input type="text" size="mini" v-model="queryModel.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input type="text" size="mini" v-model="queryModel.phone"></el-input>
        </el-form-item>
        <el-form-item label="身份证" prop="idCard">
          <el-input type="text" size="mini" v-model="queryModel.idCard"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="ios-search"
            @click="handleQuery"
            :loading="loading"
          >查询</el-button>&nbsp;
          <el-button
            type="info"
            size="mini"
            style="margin-left: 8px"
            @click="handleReset('queryForm')"
          >重置</el-button>&nbsp;
        </el-form-item>
      </div>
      <div>
        <el-form-item label="单位" prop="parentId">
          <el-select-tree
            size="mini"
            :props="props"
            :options="companyResult"
            v-model="queryModel.parentId"
            height="200"
          ></el-select-tree>&nbsp;
          <el-checkbox v-model="queryModel.subordinate">是否包含下级单位</el-checkbox>
        </el-form-item>
        <el-form-item label="绑定设备名称" prop="deviceId">
          <el-select
            v-model="queryModel.deviceId"
            size="mini"
            filterable
            clearable
            remote
            style="width:220px;"
            placeholder="请输入关键词"
            :remote-method="queryDevice"
          >
            <el-option
              v-for="device in deviceResult"
              :key="device.id"
              :label="device.aliasName"
              :value="device.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否上传照片" prop="isUploadPhoto">
          <el-select
            v-model="queryModel.isUploadPhoto"
            size="mini"
            filterable
            placeholder="请选择"
            style="width:120px"
          >
            <el-option value label="全部"></el-option>
            <el-option value="1" label="已上传"></el-option>
            <el-option value="0" label="未上传"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否同步" prop="isBound">
          <el-select
            v-model="queryModel.isBound"
            size="mini"
            filterable
            placeholder="请选择"
            style="width:120px"
          >
            <el-option value label="全部"></el-option>
            <el-option value="1" label="已同步"></el-option>
            <el-option value="0" label="未同步"></el-option>
          </el-select>
        </el-form-item>
      </div>
      <!-- <div>
        <el-form-item v-if="position1Show" :label="position1" prop="position1">
          <el-input type="text" size="mini" v-model="queryModel.position1"></el-input>
        </el-form-item>
        <el-form-item v-if="position2Show" :label="position2" prop="position2">
          <el-input type="text" size="mini" v-model="queryModel.position2"></el-input>
        </el-form-item>
        <el-form-item v-if="position3Show" :label="position3" prop="position3">
          <el-input type="text" size="mini" v-model="queryModel.position3"></el-input>
        </el-form-item>
        <el-form-item v-if="position4Show" :label="position4" prop="position4">
          <el-input type="text" size="mini" v-model="queryModel.position4"></el-input>
        </el-form-item>
        <el-form-item v-if="position5Show" :label="position5" prop="position5">
          <el-input type="text" size="mini" v-model="queryModel.position5"></el-input>
        </el-form-item>
      </div> -->
    </el-form>
    <el-divider></el-divider>
    <el-row class="button-group">
      <el-button
        type="primary"
        size="small"
        plain
        icon="el-icon-refresh"
        :disabled="multipleSelection.length==0"
        @click="dataSync"
      >数据同步</el-button>
    </el-row>
    <el-table
      ref="formTable"
      :data="tableData"
      v-loading="loading"
      stripe
      :height="tableHeight"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="personInfo.id" label="序号" width="80" fixed="left"></el-table-column>
      <el-table-column prop="personInfo.name" label="姓名" width="80" fixed="left"></el-table-column>
      <el-table-column prop="personInfo.faceImageUrl" label="人员照片" width="80" fixed="left">
        <template v-if="row.personInfo.faceImageUrl" slot-scope="{row}">
          <a :href="row.personInfo.faceImageUrl" target="_blank">
            <el-avatar
              :size="48"
              shape="circle"
              :src="row.personInfo.faceImageUrl+'?x-oss-process=image/resize,m_fill,w_64,h_64'"
              :key="row.personInfo.id"
            ></el-avatar>
          </a>
        </template>
      </el-table-column>
      <el-table-column prop="personInfo.companyName" label="单位" width="250"></el-table-column>
      <el-table-column prop="personInfo.phone" label="手机号" width="180"></el-table-column>
      <el-table-column prop="personInfo.idCard" label="身份证" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="deviceInfo.aliasName" label="绑定设备" width="150" show-overflow-tooltip></el-table-column>
      <el-table-column prop="isBound" label="是否同步到设备" width="150" show-overflow-tooltip>
        <template slot-scope="{row}">{{row.isBound ? "是" : "否"}}</template>
      </el-table-column>
      <el-table-column
        prop="personInfo.position1"
        :label="position1"
        width="180"
        v-if="position1Show"
      ></el-table-column>
      <el-table-column
        prop="personInfo.position2"
        :label="position2"
        width="180"
        v-if="position2Show"
      ></el-table-column>
      <el-table-column
        prop="personInfo.position3"
        :label="position3"
        width="180"
        v-if="position3Show"
      ></el-table-column>
      <el-table-column
        prop="personInfo.position4"
        :label="position4"
        width="180"
        v-if="position4Show"
      ></el-table-column>
      <el-table-column
        prop="personInfo.position5"
        :label="position5"
        width="180"
        v-if="position5Show"
      ></el-table-column>
      <el-table-column prop="personInfo.openId" label="是否绑定公众号" width="180">
        <template slot-scope="{row}">{{row.personInfo.openId == null ? "否" : "是"}}</template>
      </el-table-column>
      <!-- <el-table-column prop="personInfo.faceBound" label="是否同步人脸信息" width="180">
        <template slot-scope="{row}">{{row.personInfo.faceBound ? "是" : "否"}}</template>
      </el-table-column>-->
      <el-table-column prop="personInfo.popedom" label="用户身份" width="200">
        <template slot-scope="{row}">
          <el-row>
            <el-col :span="10" v-if="row.personInfo.popedom.indexOf('1')!= -1">个人用户</el-col>
            <el-col :span="10" v-if="row.personInfo.popedom.indexOf('2')!= -1">单位管理员</el-col>
            <el-col :span="10" v-if="row.personInfo.popedom.indexOf('3')!= -1">监管专员</el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="人脸授权">
        <template slot-scope="{row}">
          <el-switch
            v-model="row.personInfo.faceEnabled"
            active-color="#13ce66"
            inactive-color="#ff4949"
            disabled
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="刷卡授权">
        <template slot-scope="{row}">
          <el-switch
            v-model="row.personInfo.cardEnabled"
            active-color="#13ce66"
            inactive-color="#ff4949"
            disabled
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="手机授权">
        <template slot-scope="{row}">
          <el-switch
            v-model="row.personInfo.appEnabled"
            active-color="#13ce66"
            inactive-color="#ff4949"
            disabled
          ></el-switch>
        </template>
      </el-table-column>
      <!-- <el-table-column label="密码">
        <template slot-scope="{row}">
          <el-switch v-model="row.passwordEnabled" @change="enabledTo(row.id,'face')" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
        </template>
      </el-table-column>-->
      <el-table-column label="访客授权">
        <template slot-scope="{row}">
          <el-switch
            v-model="row.personInfo.guestEnabled"
            active-color="#13ce66"
            inactive-color="#ff4949"
            disabled
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="接收微信通知">
        <template slot-scope="{row}">
          <el-switch
            v-model="row.personInfo.wechatNoticeEnabled"
            active-color="#13ce66"
            inactive-color="#ff4949"
            disabled
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="80" fixed="right">
        <template slot-scope="{row}">
          <el-row>
            <el-col>
              <span v-if="row.isBound">
                <el-link
                  type="primary"
                  :underline="false"
                  :disabled="true"
                  @click="uploadData(row)"
                >数据同步</el-link>
              </span>
              <span v-else>
                <el-link type="primary" :underline="false" @click="uploadData(row)">数据同步</el-link>
              </span>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page.sync="pageIndex"
      :total="totalElements"
      :page-sizes="pageSizeList"
      @current-change="changePage"
      @size-change="pageSizeChange"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
  </div>
</template>
<script>
import Constant from "@/constant";

import personInfoApi from "@/api/base/personInfo";
import companyInfoApi from "@/api/base/companyInfo";
import companyPositionApi from "@/api/base/companyPosition";
import deviceInfoApi from "@/api/base/deviceInfo";
import personDeviceRelationApi from "@/api/base/personDeviceRelation";
import SelectTree from "@/components/SelectTree";

import { getToken } from "@/utils/auth"; // get token from cookie
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style

export default {
  name: "BaseDevicePersonList",
  data() {
    var self = this;

    return {
      ruleValidate: {
        parentId: [{ required: true, message: "请选择单位", trigger: "blur" }],
        deviceId: [{ required: true, message: "请选择设备", trigger: "blur" }]
      },
      queryModel: {
        companyCode: "",
        parentId: "",
        name: "",
        phone: "",
        idCard: "",
        isBound: "",
        isUploadPhoto: "",
        subordinate: false,
        position1: "",
        position2: "",
        position3: "",
        position4: "",
        position5: "",
        deviceId: ""
      },
      loading: false,
      tableData: [],
      pageIndex: 1,
      pageSize: 30,
      totalPages: 0,
      totalElements: 0,
      field: "",
      direction: "",
      pageSizeList: [30, 100, 500],
      multipleSelection: [],
      showModal: false,
      modalTitle: "",
      businessKey: "",
      companyResult: [],
      uploadCompanyId: "",
      batchImportVisible: false,
      batchImportFileList: [],
      disabled: false,
      position1: "",
      position2: "",
      position3: "",
      position4: "",
      position5: "",
      position1Show: false,
      position2Show: false,
      position3Show: false,
      position4Show: false,
      position5Show: false,
      personId: "",
      deviceResult: [],
      boundDeviceId: "",
      boundUnDeviceId: "",
      xlsLoading: false,
      tableHeight: 400,
      boundDeviceDisabled: false,
      treeData: [],
      props: {
        // 配置项（必选）
        value: "id",
        label: "name",
        children: "children"
      }
    };
  },
  created() {
    var self = this;

    companyInfoApi.list().then(function(response) {
      var jsonData = response.data;
      if (jsonData.result) {
        if (jsonData.data != null && jsonData.data != "") {
          self.companyResult = jsonData.data;
        }
      }
    });

    companyPositionApi.detailForCompany().then(function(response) {
      var jsonData = response.data.data;
      if (jsonData.position1Name != null && jsonData.position1Name != "") {
        self.position1 = jsonData.position1Name;
        self.position1Show = true;
      }
      if (jsonData.position2Name != null && jsonData.position2Name != "") {
        self.position2 = jsonData.position2Name;
        self.position2Show = true;
      }
      if (jsonData.position3Name != null && jsonData.position3Name != "") {
        self.position3 = jsonData.position3Name;
        self.position3Show = true;
      }
      if (jsonData.position4Name != null && jsonData.position4Name != "") {
        self.position4 = jsonData.position4Name;
        self.position4Show = true;
      }
      if (jsonData.position5Name != null && jsonData.position5Name != "") {
        self.position5 = jsonData.position5Name;
        self.position5Show = true;
      }
    });

    this.queryDevice("");
    this.loadTree();
  },
  methods: {
    queryDevice(aliasName) {
      var self = this;
      var formData = new FormData();
      formData.append("companyId", self.queryModel.parentId);
      formData.append("aliasName", aliasName);
      formData.append("limit", 10);

      deviceInfoApi.query(formData).then(function(response) {
        var jsonData = response.data;
        if (jsonData.result) {
          if (jsonData.data != null && jsonData.data != "") {
            self.deviceResult = jsonData.data;
          }
        }
      });
    },
    getSelectedValue(value) {
      this.queryModel.parentId = value;
    },
    loadTree() {
      var formData = new FormData();

      companyInfoApi.loadChildren(formData).then(resp => {
        var jsonData = resp.data;

        if (jsonData.result) {
          this.treeData = jsonData.data;
        } else {
          this.$message.error(jsonData.message + "");
        }
      });
    },
    loadChildren(tree, treeNode, resolve) {
      console.log(tree);

      var formData = new FormData();
      formData.append("parentId", tree.id);

      companyInfoApi.loadChildren(formData).then(resp => {
        var jsonData = resp.data;

        if (jsonData.result) {
          resolve(jsonData.data);
        } else {
          this.$message.error(jsonData.message + "");
        }
      });
    },
    handleQuery() {
      var self = this;

      this.$refs["queryForm"].validate(valid => {
        if (valid) {
          self.changePage(1);
        }
      });
    },
    changePage(pageIndex) {
      var self = this;

      self.loading = true;

      self.pageIndex = pageIndex;
      var formData = new FormData();

      formData.append("pageIndex", self.pageIndex);
      formData.append("pageSize", self.pageSize);

      if (self.queryModel.parentId == null) {
        self.queryModel.parentId = "";
      }
      formData.append("companyCode", self.queryModel.companyCode);
      formData.append("parentId", self.queryModel.parentId);

      formData.append("subordinate", self.queryModel.subordinate);

      formData.append("name", self.queryModel.name);
      formData.append("phone", self.queryModel.phone);
      formData.append("idCard", self.queryModel.idCard);
      formData.append("isBound", self.queryModel.isBound);
      formData.append("isUploadPhoto", self.queryModel.isUploadPhoto);

      formData.append("position1", self.queryModel.position1);
      formData.append("position2", self.queryModel.position2);
      formData.append("position3", self.queryModel.position3);
      formData.append("position4", self.queryModel.position4);
      formData.append("position5", self.queryModel.position5);

      formData.append("deviceId", self.queryModel.deviceId);

      if (this.field != null) {
        formData.append("field", this.field);
      }

      if (this.direction != null) {
        formData.append("direction", this.direction);
      }

      personDeviceRelationApi
        .devicePersonList(formData)
        .then(function(response) {
          self.loading = false;

          var jsonData = response.data.data;

          self.tableData = jsonData.data;
          self.totalPages = jsonData.totalPages;
          self.totalElements = jsonData.recordsTotal;

          //45为分页栏的高度
          //页面高度-列表上面的高度-分页栏高度
          self.tableHeight =
            window.innerHeight - self.$refs.formTable.$el.offsetTop - 45;
        })
        .catch(error => {
          self.loading = false;
          // self.$message.error(error + "");
        });
    },
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.changePage(this.pageIndex);
    },
    sortChange(data) {
      this.field = data.column.field;
      this.changePage(this.pageIndex);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleReset(name) {
      this.$refs[name].resetFields();
    },
    uploadData(record) {
      //同步人脸数据
      var self = this;
      self.loading = true;
      var uploadSync = new Array(0);
      uploadSync.push(record.personInfo.id);

      var formData = new FormData();
      formData.append("personId", uploadSync);
      formData.append("deviceId", record.deviceId);

      personDeviceRelationApi
        .devicePersonSync(formData)
        .then(function(response) {
          var jsonData = response.data;
          self.loading = false;
          if (jsonData.result) {
            if (jsonData.data) {
              self.changePage(self.pageIndex);
              self.$message({
                type: "success",
                message: "同步成功!"
              });
            } else {
              if (jsonData.message != null) {
                //下载有错误信息提示的报表
                //window.open(response.data);
                self.$message({
                  showClose: true,
                  dangerouslyUseHTMLString: true,
                  message:
                    "错误" +
                    `,<a href="${jsonData.message}" target="_blank">点击下载错误报表</a>&nbsp;`,
                  duration: 30000
                });
              }
            }
          } else {
            self.$message({
              type: "warning",
              message: jsonData.message
            });
          }
        });
    },
    dataSync() {
      //批量同步人脸
      var self = this;
      var idList = this.multipleSelection.map(record => {
        return record.personInfo.id;
      });

      this.$confirm("是否确认同步选中项？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          self.loading = true;
          var formData = new FormData();
          formData.append("personIds", idList);
          formData.append("deviceId", self.queryModel.deviceId);

          personDeviceRelationApi
            .devicePersonsSync(formData)
            .then(function(response) {
              var jsonData = response.data;
              self.loading = false;
              if (jsonData.result) {
                if (jsonData.data) {
                  self.changePage(self.pageIndex);
                  self.$message({
                    type: "success",
                    message: "同步成功!"
                  });
                } else {
                  if (jsonData.message != null) {
                    //下载有错误信息提示的报表
                    //window.open(response.data);
                    self.$message({
                      showClose: true,
                      dangerouslyUseHTMLString: true,
                      message:
                        "错误" +
                        `,<a href="${jsonData.message}" target="_blank">点击下载错误报表</a>&nbsp;`,
                      duration: 30000
                    });
                  }
                }
              } else {
                self.$message({
                  type: "warning",
                  message: jsonData.message
                });
              }
            });
        })
        .catch(() => {
          self.loading = false;
        });
    }
  },
  async mounted() {
    var self = this;
    this.queryDevice("");
  },
  components: {
    "el-select-tree": SelectTree
  }
};
</script>
<style lang="scss" scoped>
.el-breadcrumb {
  margin: 10px;
  line-height: 20px;
}

.el-divider {
  margin: 5px 0;
}

.demo-form-inline {
  margin-left: 10px;
  text-align: left;
}

.button-group {
  margin-left: 10px;
  text-align: left;
}
.el-select-dropdown__wrap .el-scrollbar__wrap {
  margin: 0px;
  max-height: 10;
  overflow: scroll;
}
</style>
