<template>
  <div class="content" v-loading="Status.fullLoading">
    <div class="topFilter">
      <div class="topTool">
        <el-button type="primary" @click="ShowEdit"
          ><el-icon> <Plus /> </el-icon>添加分享</el-button
        >
        <el-button type="danger" @click="DelShare(null, true)" :disabled="selectRows.length === 0">批量删除</el-button>
      </div>
      <br/>
      <el-form :inline="true" :model="filter" class="demo-form-inline">
        <el-form-item label="">
        

              <el-input
          v-model="filter.phonenumber"         
          placeholder="查找分享用户"
          :suffix-icon="'Search'"
          @input="Search"
        />

        </el-form-item>
        <el-form-item label="分享时间">
          <el-date-picker
            v-model="filter.Date"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD HH:mm:ss"
            date-format="YYYY/MM/DD ddd"
            time-format="A hh:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getRecordList">查询</el-button>
          <el-button link type="primary" @click="filter.Date = []">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="grid" v-loading="Status.loading">
      <el-table ref="grid" v-loading="Status.loading" border :data="List" height="calc(100vh - 320px)" @selection-change="RowSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="分享用户" align="center" prop="phonenumber" />
        <el-table-column label="分享权限" align="center" prop="permission">
          <template #default="scope">
            <div>{{ getPower(scope.row) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="分享时间" align="center" prop="createTime" />
        <el-table-column label="操作" align="center" fixed="right" width="280" class-name="small-padding fixed-width opt">
          <template #default="scope">
            <div class="center">
              <el-text class="mx-1 marginRight10" type="primary" @click.stop="powerSet(scope.row)">权限管理</el-text>

              <el-text class="mx-1" type="danger" @click.stop="DelShare(scope.row, false)">移除</el-text>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="pagin.total > 0"
        v-model:page="pagin.pageIndex"
        v-model:limit="pagin.pageSize"
        :total="pagin.total"
        @pagination="getRecordList"
      />
    </div>

    <!-- 修改权限弹窗 -->
    <el-dialog v-model="Status.ShowPowerSet" :title="'权限管理'" width="800" :draggable="true">
      <div class="form">
        <el-form :model="cEdit" ref="ruleFormRef" style="max-width: 750px">
          <el-form-item label="分享权限" label-position="right">
            <el-checkbox-group v-model="cEdit.permission">
              <el-checkbox :label="item.label" v-for="item in power" :value="item.value" />
            </el-checkbox-group>
          </el-form-item>
          <!-- <el-form-item label="验证码" label-position="right">
            <el-input v-model="cEdit.smsCode" placeholder="验证码">
              <template #append
                ><div class="btnSendSms" @click.stop="sendSms">{{ time > 0 ? time + '秒后重发' : '发送验证码' }}</div></template
              >
            </el-input>
          </el-form-item> -->
        </el-form>
      </div>
      <div class="center" style="margin-top: 10px">
        <el-button type="primary" @click="SaveFormData('update')"> 确定 </el-button>
        <el-button @click="CloseEdit"> 取消 </el-button>
      </div>
    </el-dialog>

    <!-- 编辑框 -->
    <el-dialog v-model="Status.ShowEditPop" :data-val="Status.ShowEditPop" :title="'添加分享'" width="800" :draggable="true">
      <div class="form">
        <el-form :model="cEdit" ref="ruleFormRef" style="max-width: 750px" :label-width="'75px'">
          <el-form-item label="分享用户" label-position="right">
            <el-select v-model="cEdit.phonenumber" filterable allow-create  default-first-option placeholder="输入以搜索">
              <el-option v-for="item in Usrs" :key="item.phonenumber" :label="item.userName" :value="item.phonenumber" />
            </el-select>
          </el-form-item>
          <el-form-item label="分享权限" label-position="right">
            <el-checkbox-group v-model="cEdit.permission">
              <el-checkbox :label="item.label" v-for="item in power" :value="item.value" />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="验证码" label-position="right">
            <el-input v-model="cEdit.smsCode" placeholder="验证码">
              <template #append
                ><div class="btnSendSms" @click.stop="sendSms">{{ time > 0 ? time + '秒后重发' : '发送验证码' }}</div></template
              >
            </el-input>
          </el-form-item>
          <el-form-item label="备注" label-position="right">
            <el-input v-model="cEdit.remark" placeholder="请输入备注" type="textarea" show-word-limit :rows="5" maxlength="50" />
          </el-form-item>
        </el-form>
      </div>
      <div class="center" style="margin-top: 10px">
        <el-button type="primary" @click="SaveFormData('add')"> 确定 </el-button>
        <el-button @click="CloseEdit()"> 取消 </el-button>
      </div>
    </el-dialog>

    <!-- 提示框 -->
    <el-dialog :width="300" :draggable="true" v-model="Status.confirm.Visible" :title="Status.confirm.title" width="500" center>
      <span>
        {{ Status.confirm.text }}
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="Status.confirm.OkCallback"> 确定 </el-button>
          <el-button v-show="Status.confirm.showCancel" @click="Status.confirm.cancelCallback">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import request from '@/utils/request';
import common from '@/utils/common';
import api from '@/api/equipmentManagement/device/shareManage';
import { dataURLtoImage } from 'image-conversion';
const props = defineProps({
  data: {
    type: Object,
    required: true
  },
  acIndex: {
    type: Number,
    required: true
  }
});

var filter = ref({
  Date: [],
  phonenumber: ''
});

var Status = reactive({
  loading: false,
  fullLoading: false,
  confirm: {
    //弹出框的配置
    Visible: false,
    title: '',
    text: '',
    cancelCallback: null,
    OkCallback: null,
    showCancel: true
  },
  ShowEditPop: false, //是否显示编辑弹窗
  ShowPowerSet: false //是否显示权限管理
});

var deviceid = null;

var data = ref({});

var grid = ref(null);
//主数据
var List = ref([]);

//所有用户
var Usrs = ref([]);

var pagin = ref({
  total: 0,
  pageIndex: 1,
  pageSize: 10
});

//当前正在编辑的数据
var cEdit = reactive({
  phonenumber: '',
  permission: [],
  remark: '',
  smsCode: ''
});

//权限字典
var dic = reactive({
  '1': '灯光模式',
  '2': '激光模式',
  '3': '开机画面',
  '4': '人员信息登记',
  '5': '发送信息',
  '6': '产品信息',
  '41':'静电探测',
  '42':'SOS'
});


var power =ref([]); 

function calcPower() {
  

  let array = [{
				value: "1",
				label: "灯光模式",
				checked: false,
				type: ['BJQ6170', 'HBY670','HBY102','BJQ6155','HBY650','BJQ7305','61XH55']
			},
			{
				value: "2",
				label: "激光模式",
				checked: false,
				type: ['BJQ6170']
			},
			{
				value: "3",
				label: "开机画面",
				checked: false,
				type: ['HBY210', 'BJQ6170', 'HBY670','BJQ6155','HBY650','BJQ7305','61XH55']
			},
			{
				value: "4",
				label: "人员信息登记",
				checked: false,
				type: ['HBY210', 'BJQ6170', 'HBY670','BJQ6155','HBY650','BJQ7305','61XH55']
			},
			{
				value: "5",
				label: "发送信息",
				checked: false,
				type: ['HBY210', 'BJQ6170', 'HBY670']
			},
			{
				value: "6",
				label: "产品信息",
				checked: false,
				type: ['HBY210', 'BJQ6170', 'HBY670']
			}, {
				value: "41",
				label: "静电探测",
				checked: false,
				type: ['HBY670','HBY650']
			}, {
				value: "42",
				label: "SOS",
				checked: false,
				type: ['HBY670','BJQ4877']
			},
			{
				value: "43",
				label: "联机设备",
				checked: false,
				type: ['HBY210']
			},
				{
				value: "44",
				label: "报警声音",
				checked: false,
				type: ['HBY210']
			},
				{
				value: "45",
				label: "自动报警",
				checked: false,
				type: ['HBY210']
			},
				{
				value: "46",
				label: "手动报警",
				checked: false,
				type: ['HBY210','HBY102']
			},
				{
				value: "47",
				label: "报警时长",
				checked: false,
				type: ['HBY210']
			},
			{
				value: "48",
				label: "物体感应",
				checked: false,
				type: ['HBY102']
			},
			{
				value: "49",
				label: "联机模式",
				checked: false,
				type: ['HBY102']
			},
			
			{
				value: "50",
				label: "报警模式",
				checked: false,
				type: ['HBY100','HBY100-J']
			},
			
			{
				value: "51",
				label: "警示灯",
				checked: false,
				type: ['HBY100','HBY100-J']
			},
			
			{
				value: "52",
				label: "语音管理",
				checked: false,
				type: ['HBY100','HBY100-J']
			},
			
			{
				value: "53",
				label: "箭头模式",
				checked: false,
				type: ['BJQ4877']
			},
			{
				value: "54",
				label: "配组设置",
				checked: false,
				type: ['BJQ4877']
			},
			{
				value: "55",
				label: "修改信道",
				checked: false,
				type: ['BJQ4877']
			},
			{
				value: "56",
				label: "灯光类型设置",
				checked: false,
				type: ['HBY100-J']
			}
		];

     
let f=array.filter(v=>{
 if(v.type.indexOf(data.value.typeName)>-1){
  return true;
 }
 return false;
})

power.value=f;

  // let arr = [];
  // let keys = Object.keys(dic);

  // keys.forEach((key) => {
  //   arr.push({ label: dic[key], value: key });
  // });
  // return arr;
};


//打开编辑
function ShowEdit() {
  Status.ShowEditPop = true;
  getUsrs();
  calcPower();
}
//关闭编辑
function CloseEdit() {
  Status.ShowEditPop = false;
  Status.ShowPowerSet = false;
  cEdit.phonenumber="";
  cEdit.permission= [];
  cEdit.remark= '';
  cEdit.smsCode= '';
}

//添加分享

//保存分享数据
function SaveFormData(type) {

  if(!cEdit.phonenumber){

    alert("请输入或选择手机号");
    return ;
  }

  let reg=/^1\d{10}$/
  if(reg.test(cEdit.phonenumber)){
    alert("手机号格式不正确");
    return;
  }

    let data = {
    'deviceId': deviceid,
    'phonenumber': cEdit.phonenumber,
    'permission': cEdit.permission.join(','),
    'shareUser': '',
    'remark': cEdit.remark,
    'smsCode': cEdit.smsCode
  };
  Status.fullLoading = true;
  api
    .SaveShare(data, type)
    .then((res) => {
      if (res.code == 200) {
        getRecordList();
        CloseEdit();
         Status.fullLoading = false;
      }
      alert(res.msg);
    })
    .catch((ex) => {
      console.log('出现异常', ex);
    })
}

function getPower(item) {
  
  let str = [];
  if (item && item.permission) {
    let arr = item.permission.split(',');

    arr.forEach((k) => {
      str.push(dic[k]);
    });
  }

  return str.join(',');
}
//批量删除

var selectRows = computed(() => {
  let arr = getSelectionRows(grid);
  return arr;
});

function DelShare(item, isBatch) {
  let arr = [];
  if (isBatch) {
    arr = getSelectionRows(grid);
  } else {
    arr = [item];
  }
  if (arr.length === 0) {
    alert('请选择需要删除的数据');
    return;
  }
  
  let OkDel = () => {
    hideConfirm();
    Status.fullLoading = true;
    setTimeout(() => {
      let ids = arr
        .map((v) => {
          return v.id;
        })
        .join(',');
      api
        .DelShare(ids)
        .then((res) => {
          if (res.code == 200) {
            getRecordList();
          }
          hideConfirm();
          alert(res.msg);
        })
        .catch((ex) => {
          console.log('ex=', ex);
        })
        .finally(() => {
          Status.fullLoading = false;
        });
    }, 0);
  };
  confirm('您确认删除选择的' + arr.length + '条数据吗?', OkDel, hideConfirm, '提示');
}

let timeOut = null;
let time = ref(0);
let timeIntval = null;
function sendSms() {
  if (time.value > 0) {
    return;
  }
  if (timeIntval) {
    return;
  }
  clearTimeout(timeOut);
  timeOut = setTimeout(() => {
    api
      .sendSms(cEdit.phonenumber)
      .then((res) => {
        if (res.code == 200) {
          console.log('res=', res);
          time.value = 60;
          timeIntval = setInterval(() => {
            time.value = time.value - 1;
            if (time.value == 0) {
              clearInterval(timeIntval);
              timeIntval = null;
            }
          }, 1000);
        }
      })
      .catch((ex) => {
        console.log('ex=', ex);
      })
      .finally(() => {});
  }, 500);
}
//权限设置
function powerSet(item) {
  
  Status.ShowPowerSet = true;
  cEdit.permission = item.permission.split(',');
  cEdit.phonenumber = item.phonenumber;
  cEdit.remark = item.remark;
  cEdit.smsCode = '';
}

function getUsrs() {
  if (Usrs.value && Usrs.value.length > 0) {
    return;
  }
  api.getUsrs().then((res) => {
    if (res.code == 200) {
      Usrs.value = res.rows;
    }
  });
}

function RowSelectionChange(row) {}
var getSelectionRows = (gridInstance) => {
  if (gridInstance.value) {
    // 检查ref是否已正确引用组件实例
    var selectedRows = gridInstance.value.getSelectionRows(); // 获取选中行数据数组
    return selectedRows;
  }
  return [];
};

let searchTime=null;
function Search(){
   clearTimeout(searchTime);
   searchTime=setTimeout(()=>{
      getRecordList();
   },500);
}

function getRecordList() {
  Status.loading = true;

  setTimeout(() => {
    initData(props.data, true);
  }, 0);
}

function initData(item, Refresh) {
  if (deviceid == item.data.deviceId && !Refresh) {
    Status.loading = false;
    return;
  }
  
  List.value = [];

  deviceid = item.data.deviceId;
  let params = {
    deviceId: item.data.deviceId,
    shareStartTime: '',
    shareEndTime: '',
    phonenumber: filter.value.phonenumber,
    pageSize: pagin.value.pageSize,
    pageNum: pagin.value.pageIndex,
    orderByColumn: 'createTime',
    isAsc: 'descending'
  };

  if (filter.value.Date && filter.value.Date.length) {
    params.shareStartTime = common.DateFormat(filter.value.Date[0], null);
    params.shareEndTime = common.DateFormat(filter.value.Date.length > 1 ? filter.value.Date[1] : '', null);
  }

  api
    .searchShare(params)
    .then((res) => {
      if (res.code == 200) {
        if (res.rows) {
          if (res.rows.length) {
            List.value = res.rows;
          }
        }
        pagin.value.total = res.total;
      }
    })
    .finally(() => {
      data.value = item.data;
      Status.loading = false;
    });
}

window.confirm = function (text, OK, cancel, title) {
  let Cfg = {
    Visible: true,
    title: title ? title : '提示',
    text: text ? text : '此操作不可逆，您确定这样做吗？',
    OkCallback: () => {
      Status.confirm.Visible = false;
      if (OK) {
        OK();
      }
    },
    showCancel: true,
    cancelCallback: () => {
      Status.confirm.Visible = false;
      if (cancel) {
        cancel();
      }
    }
  };

  Status.confirm = Cfg;
};

window.alert = function (text, OK, title) {
  let Cfg = {
    Visible: true,
    title: title ? title : '提示',
    text: text ? text : '不符合规则',
    OkCallback: () => {
      Status.confirm.Visible = false;
      if (OK) {
        OK();
      }
    },
    showCancel: false,
    cancelCallback: null
  };

  Status.confirm = Cfg;
};

var hideConfirm = function () {
  let Cfg = {
    Visible: false,
    title: '提示',
    text: '',
    cancelCallback: null,
    OkCallback: null,
    showCancel: false
  };

  Status.confirm = Cfg;
};
window.hideConfirm = hideConfirm;
window.hideAlert = hideConfirm;

watch(
  () => props.acIndex, // 监听的属性
  (newVal) => {
    if (newVal === 5) {
      // 确保参数有效

      console.log('newVal=', newVal);
      getRecordList(); // 调用回调
    }
  },
  { immediate: true } // 关键：组件初始化时立即执行一次
);
</script>
<style lang="scss" scoped>
.content {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 12px 12px 12px 12px;
}
.center {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  align-items: center;
  justify-content: center;
}
.pickerContent {
  box-sizing: border-box;
  border: 1px solid rgba(189, 198, 215, 0.8);
  border-radius: 2px;
}
.topFilter {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: space-between;
  align-items: flex-start;
  
  
}
:deep .pickerContent .el-date-editor {
  border: none !important;
}

.marginRight10 {
  margin-right: 10px;
}
.mx-1 {
  cursor: pointer;
}

.btnSendSms {
  background-color: #409eff;
  color: #ffffff;
  padding: 0px 20px;
  cursor: pointer;
}

:deep .el-overlay .el-input-group__append {
  padding: 0px !important;
}

:deep .topFilter .el-input-group__append {
  padding: 0px 10px !important;
}
.topTool{
      display: flex
;
    flex-direction: row;
    flex-wrap: nowrap;
    align-content: center;
    justify-content: flex-start;
    align-items: center;
}
</style>
