<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,
  addUploadFile
} from "../../../api/safetyMangement/weekDictionaries";

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.sysDefault
    }
  },
  { prop: "name", label: "字典名称", align: "left", slotName: "name" },
  {
    prop: "createBy",
    label: "所属用户",
    align: "left",
  },
  {
    prop: "gmtModified",
    label: "更新时间",
    align: "left",
  },
  {
    label: "操作",
    fixed: "right",
    width: "160px",
    buttons: [
      {
        title: "编辑",
        hide: () => {
          if (butomData.value.indexOf("编辑") > -1) {
            return true;
          }
        },
        disabled(row){
          return row.sysDefault
        }
      },
      {
        title: "删除",
        hide: () => {
          if (butomData.value.indexOf("删除") > -1) {
            return true;
          }
        },
        disabled(row){
          return row.sysDefault
        }
      },
    ],
  }
];
/**
 * @description: 新增抽屉
 */
const drawerProps = reactive({
  showDrawer: false,
  title: "新增",
  size: "small",
});
const dialogForm = ref();
const form = reactive({
  name: "",
  type: 'standard',
  weakPass: '',
  username: ''
});
const disabled = ref(false);
const formRules = reactive<FormRules>({
  name: [
    { required: true, message: "字典名称不能为空", trigger: "change" },
    { max: 30, message: "字典名称最多30位" },
  ],
  username: [
    { required: true, message: "用户字典不能为空", trigger: "change" },
  ],
  weakPass: [
    { required: true, message: "密码字典不能为空", trigger: "change" },
  ]
});

/**
 * @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: 初始化form值
 */
const resetForm = () => {
  form.name = "";
  form.type = 'standard';
  form.weakPass = '';
  form.username = '';
  form.id = '';
  selectValue.value = '1'
}
/**
 * @description: 关闭抽屉
 */
 const handleCloseDrawer = async () => {
  resetForm()
  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: 新增/编辑提交
 * @param {'add': 新增, 'allDel': '批量删除', 'edit': '编辑', 'del': '删除'}
 */
const autoBtn = (e,row) => {
  switch (e) {
    case 'add':
      resetForm()
      drawerProps.title = "新增";
      drawerProps.showDrawer = true;
      disabled.value = false
    break
    case 'edit':
      drawerProps.title = "编辑";
      drawerProps.showDrawer = true;
      disabled.value = false;
      form.id = row.id;
      form.name = row.name;
      form.weakPass = row.config.weakPass;
      form.username = row.config.username;
      if (form.weakPass && form.username) {
        form.type = 'standard';
      } else {
        form.type = 'mix';
      }
    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 = "详情";
      drawerProps.showDrawer = true;
      disabled.value = true;
      form.name = row.name;
      form.weakPass = row.config.weakPass;
      form.username = row.config.username;
      if (form.weakPass && form.username) {
        form.type = 'standard';
      } else {
        form.type = 'mix';
      }
    break
  }
}
/**
 * @description: 新增/编辑提交确定
 */
const handleSubmit = async () => {
  let send;
  if (drawerProps.title == "新增") {
    send = create
    delete form.id
  } else {
    send = modify
  }
  let parms = {
    ...form
  }
  if (form.type == 'standard') {
    if (!form.username) return ElMessage.warning('用户字典不能为空!')
    if (!form.weakPass) return ElMessage.warning('密码字典不能为空!')
  } else {
    if (!form.weakPass) return ElMessage.warning('组合字典不能为空!')
    delete parms.username
  }
  let res = await send(parms);
  if (res.code == 200) {
    ElMessage.success(drawerProps.title + '成功!')
    drawerProps.showDrawer = false;
    getTableData();
  }
  console.log(res)
}
/**
 * @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;
    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");
};
/**
 * 按钮权限
 */
 const btnPower = () => {
  permissionsButtons.map((item) => {
    butomData.value.push(item.label);
  });
  if (butomData.value.indexOf("新增") > -1) {
    rightButtons.value.push({
      text: "新增",
      type: "primary",
      eventName: function () {
        autoBtn("add");
      },
    });
  }
  if (butomData.value.indexOf("批量删除") > -1) {
    leftButtons.value.push({
      text: "批量删除",
      type: "primary",
    });
  }
};
const formColumns = reactive([
  {
    key: "name",
    type: "input",
    label: "字典名称",
    placeholder: "请输入字典名称",
    clearable: true,
    col: 24,
    disabled: disabled
  },
  {
    key: "type",
    type: "radio",
    label: "字典模式",
    col: 24,
    options: [
      {
        key: "标准模式",
        value: 'standard',
      },
      {
        key: "组合模式",
        value: 'mix',
      }
    ],
    disabled: disabled
  },
  {
    slotName: 'username'
  },
]);
const selectValue = ref('1')
watch(
  () => form.type,
  () => {
    nextTick(()=>{
      selectValue.value = '1'
      form.weakPass = ''
    })
  }
);
const fileList = ref([])
/**
 * @description 文件上传
 */
const handleChange = async (uploadFile, uploadFiles) => {
  let flg = beforeAvatarUpload(uploadFile)
  if (flg) {
    let fd = new FormData()
    fd.append('file', uploadFile.raw)
    let res = await addUploadFile(fd);
    if (form.type == 'standard') {
      if (selectValue.value == '1') {
        form.username = res.data
      } else {
        form.weakPass = res.data
      }
    } else {
      form.weakPass = res.data
    }
  }
}
/**
 * @description 上传文件格式校验
 */
const beforeAvatarUpload = (file) => {
let testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
const extension2 = testmsg === 'txt'
if (!extension2) {
  ElMessage.error('文件上传格式不正确')
  nextTick(() => {
    let _data = fileList.value.findIndex(item => {
      return item.name == file.name
    })
    fileList.value.splice(_data, 1)
  })
  return false
} else if (file.size / 1024 / 1024 > 200) {
  ElMessage.error('单个文件最多只能上传200MB!')
  nextTick(() => {
    let _data = fileList.value.findIndex(item => {
      return item.name == file.name
    })
    fileList.value.splice(_data, 1)
  })
  return false
}
return true
}
/**
 * @description: 页面渲染结束后执行
 */
 onMounted(() => {
  btnPower();
  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="autoBtn('detail',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 #username="{ item }" >
          <div v-if="form.type == 'standard'" class="width100">
            <div class="form-label">
              <!-- <span class="must-icon">*</span>  -->
              用户字典 
              <el-tooltip
                placement="right"
                content="添加多个用户名时，通过','进行分隔"
              >
              <svg t="1660879085342" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2208" width="14" height="14"><path d="M543.317333 650.837333c-6.656 8.106667-15.189333 13.909333-19.114666 12.202667-3.754667-1.450667-5.973333-5.888-4.864-10.24l53.845333-197.034667a43.52 43.52 0 0 0-5.717333-34.218666 34.986667 34.986667 0 0 0-27.733334-16.213334 140.373333 140.373333 0 0 0-91.392 72.106667 217.6 217.6 0 0 0 0 24.064l32.256-43.008c6.741333-8.106667 14.677333-13.909333 18.602667-12.544 4.010667 1.877333 6.144 6.826667 4.864 11.52L450.133333 653.653333c-6.058667 22.698667 5.546667 45.312 34.133334 50.432 41.813333 0 66.730667-31.146667 91.306666-71.424a215.296 215.296 0 0 0 0-24.746666l-32.256 43.008zM543.744 256c-17.664 0.170667-31.914667 17.066667-31.744 37.632 0.170667 20.650667 14.592 37.205333 32.256 37.034667 17.664-0.170667 31.914667-17.066667 31.744-37.632a39.68 39.68 0 0 0-9.386667-26.624A29.013333 29.013333 0 0 0 543.829333 256z" p-id="2209"></path><path d="M512 53.333333a458.666667 458.666667 0 1 0 0 917.333334A458.666667 458.666667 0 0 0 512 53.333333z m0 64a394.666667 394.666667 0 1 1 0 789.333334 394.666667 394.666667 0 0 1 0-789.333334z" p-id="2210"></path></svg>
              </el-tooltip>
            </div>
            <el-input
              class="margin-bottom12"
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 8}"
              :disabled="disabled"
              placeholder="请输入内容"
              v-model="form.username">
            </el-input>
            <div class="form-label">
              <!-- <span class="must-icon">*</span> -->
               密码字典
               <el-tooltip
                placement="right"
                content="添加多个密码时，通过','进行分隔"
              >
              <svg t="1660879085342" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2208" width="14" height="14"><path d="M543.317333 650.837333c-6.656 8.106667-15.189333 13.909333-19.114666 12.202667-3.754667-1.450667-5.973333-5.888-4.864-10.24l53.845333-197.034667a43.52 43.52 0 0 0-5.717333-34.218666 34.986667 34.986667 0 0 0-27.733334-16.213334 140.373333 140.373333 0 0 0-91.392 72.106667 217.6 217.6 0 0 0 0 24.064l32.256-43.008c6.741333-8.106667 14.677333-13.909333 18.602667-12.544 4.010667 1.877333 6.144 6.826667 4.864 11.52L450.133333 653.653333c-6.058667 22.698667 5.546667 45.312 34.133334 50.432 41.813333 0 66.730667-31.146667 91.306666-71.424a215.296 215.296 0 0 0 0-24.746666l-32.256 43.008zM543.744 256c-17.664 0.170667-31.914667 17.066667-31.744 37.632 0.170667 20.650667 14.592 37.205333 32.256 37.034667 17.664-0.170667 31.914667-17.066667 31.744-37.632a39.68 39.68 0 0 0-9.386667-26.624A29.013333 29.013333 0 0 0 543.829333 256z" p-id="2209"></path><path d="M512 53.333333a458.666667 458.666667 0 1 0 0 917.333334A458.666667 458.666667 0 0 0 512 53.333333z m0 64a394.666667 394.666667 0 1 1 0 789.333334 394.666667 394.666667 0 0 1 0-789.333334z" p-id="2210"></path></svg>
              </el-tooltip>
            </div>
            <el-input
              class="margin-bottom12"
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 8}"
              placeholder="请输入内容"
              :disabled="disabled"
              v-model="form.weakPass">
            </el-input>
          </div>
          <div v-if="form.type == 'mix'" class="width100">
            <div class="form-label">
              <!-- <span class="must-icon">*</span>  -->
              组合字典
              <el-tooltip
                placement="right"
              >
              <template #content> 用户名密码之间请用-;-隔开，如-user:pwd-<br />添加多个用户名/密码时，通过','进行分隔。</template>
              <svg t="1660879085342" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2208" width="14" height="14"><path d="M543.317333 650.837333c-6.656 8.106667-15.189333 13.909333-19.114666 12.202667-3.754667-1.450667-5.973333-5.888-4.864-10.24l53.845333-197.034667a43.52 43.52 0 0 0-5.717333-34.218666 34.986667 34.986667 0 0 0-27.733334-16.213334 140.373333 140.373333 0 0 0-91.392 72.106667 217.6 217.6 0 0 0 0 24.064l32.256-43.008c6.741333-8.106667 14.677333-13.909333 18.602667-12.544 4.010667 1.877333 6.144 6.826667 4.864 11.52L450.133333 653.653333c-6.058667 22.698667 5.546667 45.312 34.133334 50.432 41.813333 0 66.730667-31.146667 91.306666-71.424a215.296 215.296 0 0 0 0-24.746666l-32.256 43.008zM543.744 256c-17.664 0.170667-31.914667 17.066667-31.744 37.632 0.170667 20.650667 14.592 37.205333 32.256 37.034667 17.664-0.170667 31.914667-17.066667 31.744-37.632a39.68 39.68 0 0 0-9.386667-26.624A29.013333 29.013333 0 0 0 543.829333 256z" p-id="2209"></path><path d="M512 53.333333a458.666667 458.666667 0 1 0 0 917.333334A458.666667 458.666667 0 0 0 512 53.333333z m0 64a394.666667 394.666667 0 1 1 0 789.333334 394.666667 394.666667 0 0 1 0-789.333334z" p-id="2210"></path></svg>
              </el-tooltip>
            </div>
            <el-input
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 8}"
              :disabled="disabled"
              placeholder="请输入内容"
              v-model="form.weakPass">
            </el-input>
          </div>
          <div class="width100">
            <div class="form-label">
              从文件导入
              <el-tooltip
                placement="right"
                content="文件导入仅支持TXT格式"
              >
              <svg t="1660879085342" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2208" width="14" height="14"><path d="M543.317333 650.837333c-6.656 8.106667-15.189333 13.909333-19.114666 12.202667-3.754667-1.450667-5.973333-5.888-4.864-10.24l53.845333-197.034667a43.52 43.52 0 0 0-5.717333-34.218666 34.986667 34.986667 0 0 0-27.733334-16.213334 140.373333 140.373333 0 0 0-91.392 72.106667 217.6 217.6 0 0 0 0 24.064l32.256-43.008c6.741333-8.106667 14.677333-13.909333 18.602667-12.544 4.010667 1.877333 6.144 6.826667 4.864 11.52L450.133333 653.653333c-6.058667 22.698667 5.546667 45.312 34.133334 50.432 41.813333 0 66.730667-31.146667 91.306666-71.424a215.296 215.296 0 0 0 0-24.746666l-32.256 43.008zM543.744 256c-17.664 0.170667-31.914667 17.066667-31.744 37.632 0.170667 20.650667 14.592 37.205333 32.256 37.034667 17.664-0.170667 31.914667-17.066667 31.744-37.632a39.68 39.68 0 0 0-9.386667-26.624A29.013333 29.013333 0 0 0 543.829333 256z" p-id="2209"></path><path d="M512 53.333333a458.666667 458.666667 0 1 0 0 917.333334A458.666667 458.666667 0 0 0 512 53.333333z m0 64a394.666667 394.666667 0 1 1 0 789.333334 394.666667 394.666667 0 0 1 0-789.333334z" p-id="2210"></path></svg>
              </el-tooltip>
            </div>
            <div>
              <el-select
                :disabled="disabled"
                v-model="selectValue"
                placeholder="请选择"
              >
                <el-option key="1" value="1" label="导入用户字典" v-if="form.type == 'standard'"></el-option>
                <el-option key="2" value="2" label="导入密码字典" v-if="form.type == 'standard'"></el-option>
                <el-option key="1" value="1" label="导入组合字典" v-if="form.type == 'mix'"></el-option>
              </el-select>
            </div>
            <div class="export">
              <el-upload
                :disabled="disabled"
                :before-upload="beforeAvatarUpload"
                :file-list="fileList"
                :show-file-list="false"
                :on-change="handleChange"
                :auto-upload="false"
                action=""
              >
                <div class="export-file">
                  <div class="export-file-one">请选择</div>
                  <div class="export-file-img">
                    <img
                      src="../../../assets/image/up-load.png"
                      alt=""
                    />
                  </div>
                </div>
              </el-upload>
            </div>
          </div>
        </template>
        </ya-form>
      </template>
    </ya-drawer>
  </div>
</template>
<style lang="scss" scoped>
.detail {
  color: rgb(0, 121, 234);
  text-decoration: underline;
}
.detail:hover {
  cursor: pointer;
}
.width100 {
  width: 100%;
  position: relative;
  top: -10px;
}
.form-label {
  font-size: var(--el-form-label-font-size);
  color: var(--el-text-color-primary);
}
.must-icon {
  color: var(--el-color-danger);
}
.margin-bottom12 {
  margin-bottom: 12px;
}
.icon {
  width: 14px;
  height: 14px;
  fill: rgba(0,0,0,.65);
  position: relative;
  top: 2px;
}

.export {
  // margin-top: 24px;
  .export-file {
    margin-top: 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .export-file-one {
      background: #fff;
      height: 32px;
      line-height: 32px;
      padding: 0 8px;
      flex: 1;
      border: 1px solid #E4E4E4; 
      color: #595959;
      border-right: none;
      text-align: left;
      padding-left: 12px;
    }
    .export-file-img {
      height: 32px;
      width: 36px;
      border: 1px solid #E4E4E4; 
      // border-top-left-radius: 2px;
      // border-bottom-left-radius: 2px;
      text-align: center;
      img {
        position: relative;
        top: 5px;
      }
    }
  }
  .export-file:hover {
    cursor: pointer;
  }
  ::v-deep .el-upload {
    text-align: left;
    width: 100%;
  }
  ::v-deep .el-upload-dragger {
    padding: 0;
    border: none;
    border-radius: 0;
  }
}
</style>
