<script lang="ts" setup>
import { ref, reactive, onMounted, watch, nextTick, unref } from "vue";
import { ElMessage, ElMessageBox, FormRules } from "element-plus";
import { usePermissions } from "../../../composables/usePermissions";
import {
  getList,
  create,
  modify,
  deleteOne,
  deleteSome,
  getServiceList,
  getDictList
} from "../../../api/safetyMangement/weekPolicy";

const { permissionsButtons } = usePermissions();
const butomData = ref([]);
const rightButtons = ref([]);
const leftButtons = ref([]);
const tableData = ref([]);
/**
 * @description: 分页参数
 */
const page = ref(1);
const total = ref(0);
const size = ref(20);
/**
 * @description: 搜索条件
 */
const queryFormData = reactive({
  name:'',
});
const queryColumns = reactive([
  {
    key: 'name',
    type: 'input',
    label: '策略名称',
    placeholder: '请输入策略名称',
    col: 6
  }
]);
/**
 * @description:表格头部数据
 */
let tableColumn: any[] = [
  {
    type: "selection",
    width: "65px",
    selectable(e){
      return e.type != 'sysDefault'
    }
  },
  { prop: "name", label: "策略名称", align: "left", slotName: "name" },
  {
    prop: "detectCount",
    label: "探测次数",
    align: "left",
  },
  {
    prop: "createBy",
    label: "所属用户",
    align: "left",
  },
  {
    prop: "gmtCreate",
    label: "创建时间",
    align: "left",
  },
  {
    label: "操作",
    fixed: "right",
    width: "160px",
    buttons: [
      {
        title: "编辑",
        hide: () => {
          if (butomData.value.indexOf("编辑") > -1) {
            return true;
          }
        },
        disabled(row,btn){
          if (row.type == 'sysDefault') {
            return true
          } else {
            return false
          }
        }
      },
      {
        title: "删除",
        hide: () => {
          if (butomData.value.indexOf("删除") > -1) {
            return true;
          }
        },
        disabled(row,btn){
          if (row.type == 'sysDefault') {
            return true
          } else {
            return false
          }
        }
      },
    ],
  }
];
/**
 * @description: 新增抽屉
 */
const drawerProps = reactive({
  showDrawer: false,
  title: "新增",
  size: "small",
});
const dialogForm = ref();
const form = reactive({
  name: "",
  maxThread: 10,
  guessTime: 300,
  detectCount: 0,
});
const disabled = ref(false);
const isIndeterminate = ref(false);
const checkAll = ref(true);
const checkedCities = ref([]);
const cities = ref([]);
const options = ref([])
const formRules = reactive<FormRules>({
  name: [
    { required: true, message: "策略名称不能为空", trigger: "change" },
    { max: 18, message: "策略名称最多20位" },
  ],
  maxThread: [
    {
      required: true,
      message: "最大并发线程数不能为空",
      trigger: "change",
    },
    {
      validator: (rule, value, callback) => {
        if (/^(?:[0-9]\d*)$/.test(value) == false) {
          callback(new Error("请输入正整数"));
        } else if (value < 1) {
          callback(new Error("范围在1-40"));
        } else if (value > 40) {
          callback(new Error("范围在1-40"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
  guessTime: [
    {
      required: true,
      message: "口令猜测时间不能为空",
      trigger: "change",
    },
    {
      validator: (rule, value, callback) => {
        if (/^(?:[0-9]\d*)$/.test(value) == false) {
          callback(new Error("请输入正整数"));
        } else if (value < 0) {
          callback(new Error("范围在0-999"));
        } else if (value > 999) {
          callback(new Error("范围在0-999"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
  detectCount: [
    { required: true, message: "探测次数不能为空", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (/^(?:[0-9]\d*)$/.test(value) == false) {
          callback(new Error("请输入正整数"));
        } else if (value < 0) {
          callback(new Error("范围在0-999"));
        } else if (value > 999) {
          callback(new Error("范围在0-999"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
});
/**
 * @description: 通用全选
 */
const handleCheckAllChange = (val) => {
  checkedCities.value = val ? cities.value.map(item => item.id) : []
  isIndeterminate.value = false
};
/**
 * @description: 通用单选
 */
 const handleCheckedCitiesChange = (value) => {
  let checkedCount = value.length
  checkAll.value = checkedCount === cities.value.length
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < cities.value.length
};
/**
 * @description: 表格操作
 */
const tableBtnClick = (btn, row) => {
  if (btn.text == "批量删除") {
    autoBtn('allDel')
  } else if (btn.text == '新增') {
    autoBtn("add");
  } else if (btn.title == '编辑') {
    autoBtn("edit",row);
  } else if (btn.title == '删除') {
    autoBtn("del",row);
  }
};
/**
 * @description: 关闭抽屉
 */
 const handleCloseDrawer = async () => {
  form.value = {};
  drawerProps.showDrawer = false;
};
// 抽屉事件
const handleEvent = function (data) {
  if (data.eventName == "errorSubmit") {
    return;
  } else if (data.eventName == "success") {
    dialogForm.value.submitForm(dialogForm.value.ruleFormRef);
    return;
  } else if (data.eventName == "successSubmit") {
    handleSubmit();
    return;
  }
};
/**
 * @description: 新增、编辑确认
 */
const handleSubmit = () => {
  let send
  if (drawerProps.title == '新增') {
    send = create
  } else {
    send = modify
  }
  let dictConfig = cities.value.filter(e=>checkedCities.value.includes(e.id)).map((item)=>{
    let obj = {
      serviceId: item.serviceId,
      dictId: item.dictId
    }
    return obj
  })
  let parms = {
    ...form,
    dictConfig
  }
  send(parms).then(res => {
    if (res.code == 200) {
      ElMessage.success(drawerProps.title + '成功!')
      drawerProps.showDrawer = false;
      getTableData();
    }
  })
}
/**
 * @description: 新增/编辑提交
 * @param {'add': 新增,'edit': '编辑', 'del': '删除', 'allDel': '批量删除', detail: '详情'}
 */
const autoBtn = (e,row) => {
  if (e == 'add' || e == 'edit' || e == 'detail') {
    getService(row)
  }
  nextTick(()=>{
    switch (e) {
      case 'add':
        drawerProps.title = "新增";
        disabled.value = false;
        form.id = "";
        form.name = "";
        form.maxThread = 10;
        form.guessTime = 300;
        form.detectCount = 0;
      break
      case 'edit':
        drawerProps.title = "编辑";
        disabled.value = false;
        form.id = row.id;
        form.name = row.name;
        form.maxThread = row.maxThread;
        form.guessTime = row.guessTime;
        form.detectCount = row.detectCount;
      break
      case 'del':
        handleDel(row.id, 'one')
      break
      case 'allDel':
        if(selectData.value.length == 0) return ElMessage.warning('请选择要删除数据！')
        let ids = selectData.value.map((item)=>{
          return item.id
        })
        handleDel(ids, 'some')
      break
      case 'detail':
        drawerProps.title = "详情";
        disabled.value = true;
        form.id = row.id;
        form.name = row.name;
        form.maxThread = row.maxThread;
        form.guessTime = row.guessTime;
        form.detectCount = row.detectCount;
      break
    }
  })
  
}
/**
 * @description: 删除
 * @return {*}
 * @param id:id,type:one 当个删除 some 批量删除
 */
 const handleDel = async (id,type) => {
  ElMessageBox.confirm("此操作不可逆，是否要确认删除？", "提示", {
    customClass: "message-warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(() => {
    if (type == 'one') {
      deleteOne({
        id: id,
      }).then((res) => {
        if (res.code == 200) {
          ElMessage.success("删除成功");
          getTableData();
        }
      });
    } else {
      deleteSome(id).then((res) => {
        if (res.code == 200) {
          ElMessage.success("删除成功");
          getTableData();
        }
      });
    }
  });
};
/**
 * @description: 表格多选操作
 */
const selectData = ref([]);
const handleSelect = (data) => {
  selectData.value = data;
};
/**
 * @description: 获取表格数据
 * @param {*}
 * @return {*}
 */
const getTableData = async (type) => {
  if (type === "init") {
    page.value = 1;
  }
  try {
    const params = {
      pageIndex: page.value,
      pageSize: size.value,
      name: queryFormData.name
    };
    const res = await getList(params);
    if (res.code !== 200) return;
    tableData.value = res.data.records;
    console.log( tableData.value)
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
  }
};
/**
 * @description: 重置操作
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const reset = () => {
  getTableData("init");
};
/**
 * @description: 页面容量切换
 * @param {*}
 * @return {*}
 */
const sizeChange = function (val: number) {
  size.value = val;
  page.value = 1;
  getTableData("page");
};
/**
 * @description: 分页切换
 * @param {*}
 * @return {*}
 */
const currentChange = function (val: number) {
  page.value = val;
  getTableData("page");
};
/**
 * @description: 查询所有弱口令字典
 */
const getDict = () => {
  getDictList().then(res => {
    options.value = res.data.map(item => {
      return {
        label: item.name,
        value: item.id
      }
    })
  })
}
/**
 * @description: 查询所有服务查询
 */
const getService = (row) => {
  getServiceList().then(res => {
    let list = []
    if(drawerProps.title == '编辑' || drawerProps.title == '详情') {
      checkedCities.value = row.dictConfig.map((item)=>{
        return item.serviceId
      })
      cities.value = res.data.map((item) => {
        item.serviceId = item.id
        row.dictConfig.find((value) => {
          if (item.id == value.serviceId) {
            item.dictId = value.dictId
          } else {
            item.dictId = item.weakPasswordDictId
          }
        })
        return item
      })
    } else {
      cities.value = res.data.map(item => {
        item.serviceId = item.id
        item.dictId = item.weakPasswordDictId
        return item
      })
      checkedCities.value = JSON.parse(JSON.stringify(cities.value.map((item)=>{
        return item.id
      })))
    }
    let isTrue = checkedCities.value.length === cities.value.length ? true : false
    checkAll.value = isTrue
    isIndeterminate.value = !isTrue
    drawerProps.showDrawer = true;
  })
}
/**
 * @description: 重置提交数据
 */
const resetSubData = () => {
}
/**
 * 按钮权限
 */
 const btnPower = () => {
  permissionsButtons.map((item) => {
    butomData.value.push(item.label);
  });
  if (butomData.value.indexOf("新增") > -1) {
    rightButtons.value.push({
      text: "新增",
      type: "primary",
    });
  }
  if (butomData.value.indexOf("批量删除") > -1) {
      leftButtons.value.push({
        text: "批量删除",
        type: "primary",
      });
    }
};
const formColumns = reactive([
  {
    key: "name",
    type: "input",
    label: "策略名称",
    placeholder: "请输入策略名称",
    clearable: true,
    disabled: disabled
  },
  {
    label: "风险监控项-通用",
    slotName: 'monitoring'
  },
  {
    key: "detectCount",
    type: "input",
    label: "口令探测次数",
    tooltip: "可输入0-999的整数，0为不限制",
    placeholder: "请输入口令探测次数",
    clearable: true,
    disabled: disabled
  },
  {
    key: "guessTime",
    type: "input",
    label: "口令猜测时间",
    tooltip: "可输入0-999的整数（单位：秒），0为不限制",
    placeholder: "请输入口令猜测时间",
    clearable: true,
    disabled: disabled
  },
  {
    key: "maxThread",
    type: "input",
    label: "最大并发线程数",
    tooltip: "可以输入1-40的整数",
    placeholder: "请输入最大并发线程数",
    clearable: true,
    disabled: disabled
  },
]);
const toDetail = (e) => {
  autoBtn('detail', e)
}
/**
 * @description: 页面渲染结束后执行
 */
 onMounted(() => {
  btnPower();
  getDict();
  getTableData("init");
});
</script>
<template>
  <div>
    <YaPageContent
      :formData="queryFormData"
      :formColumns="queryColumns"
      searchLabelWidth="80px"
      :tableData="tableData"
      :tableColumns="tableColumn"
      :currentPage="page"
      :pageSize="size"
      :total="total"
      :leftButtons="leftButtons"
      :rightButtons="rightButtons"
      @search="reset"
      @sizeChange="sizeChange"
      @currentChange="currentChange"
      @selectionChange="handleSelect"
      @reset="reset"
      @tableBtnClick="tableBtnClick"
    >
    <template #name="{ item }">
      <div class="detail" @click="toDetail(item)">
        {{ item.name }}
      </div>
    </template>
    </YaPageContent>
    <!-- 新增/编辑 -->
    <ya-drawer
      v-if="drawerProps.showDrawer"
      :showConfirm="!disabled" 
      :drawerProps="drawerProps"
      @handleEvent="handleEvent"
      destroy-on-close
      :before-close="handleCloseDrawer"
    >
      <template #content>
        <ya-form
          label-position="top"
          @handleEvent="handleEvent"
          :formColumns="formColumns"
          labelWidth="100px"
          :formData="form"
          :rules="formRules"
          :ref="
            (el) => {
              if (el) dialogForm = el;
            }
          "
        >
        <template #monitoring="{ item }">
          <div class="all-use">
            <div class="add-chose">
              <el-checkbox
                :disabled="disabled"
                :indeterminate="isIndeterminate"
                v-model="checkAll"
                @change="handleCheckAllChange"
                >全选</el-checkbox
              >
              <el-checkbox-group
                :disabled="disabled"
                v-model="checkedCities"
                @change="handleCheckedCitiesChange"
              >
                <el-checkbox
                  v-for="item in cities"
                  :label="item.id"
                  :key="item.id"
                >
                  <span>{{ item.name }}</span>
                  <el-select
                    :disabled="disabled"
                    v-model="item.dictId"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </template>
        </ya-form>
      </template>
    </ya-drawer>
  </div>
</template>
<style lang="scss" scoped>
.form-name {
  ::v-deep .el-form-item .el-form-item__label {
    // text-align: right;
    width: 80px !important;
  }
  margin-bottom: 20px;
}
.all-use {
  // margin-left: 30px;
  // position: relative;
  // top: -10px;
  .add-chose {
    padding: 12px;
    padding-top: 0;
    // max-height: 310px;
    background: rgba(240, 244, 248, 0.5);
    border-radius: 4px;
    overflow-y: auto;
    overflow-x: hidden;
    span {
      width: 80px;
      display: inline-block;
    }
    ::v-deep .el-checkbox {
      // display: block;
      // width: 100%;
      margin-top: 12px;
    }
    ::v-deep .el-checkbox__label {
      width: 20%;
    }
    ::v-deep .el-select {
      width: 175px;
    }
    ::v-deep .el-input__inner {
      background: #fff;
      width: 100%;
    }
    ::v-deep.el-select .el-input .el-select__caret.el-icon-arrow-up::before {
      content: '';
      display: inline-block;
      // background: url('../../../../public/assets/image/img-1.png') no-repeat;
      background-size: 100%;
      position: absolute;
      width: 20px;
      height: 20px;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%) rotate(-180deg);
    }
  }
  .form {
    margin-top: 24px;
    ::v-deep .el-form-item .el-form-item__label {
      text-align: right;
    }
    ::v-deep .el-input-group__append {
      border: none;
      background: none;
      padding: 0 10px;
    }
    .el-icon-warning {
      color: #f0f4f8;
    }
    img {
      width: 16px;
      height: 16px;
    }
    img:hover {
      cursor: pointer;
    }
  }
}
.detail {
  color: rgb(0, 121, 234);
  text-decoration: underline;
}
.detail:hover {
  cursor: pointer;
}
</style>
