<template>
  <fvSearchForm :searchConfig="searchConfig" @search="searchSensitive"></fvSearchForm>
  <fvTable ref="tableIns" :tableConfig="sensitiveTableConfig"  @headBtnClick="headBtnClick" @selectionChange="selectionChange"></fvTable>
  <fvFormDialog ref="formDialogRef" :title="dialogTitle" :dialogType="dialogType"
                :form-schema="formSchema" :form-rules="formRules"
                @dialogSubmit="handleSubmitAddressBook"></fvFormDialog>
</template>

<script setup lang="jsx">
import { shallowRef } from 'vue';
import fvSelect from '@/fvcomponents/fvSelect/index.vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {addSensitive, deleteSensitive, editSensitive,getSensitiveDetail} from "@/api/sensitive-words";
const router = useRouter()
const tableIns = ref()
const formDialogRef = ref()
const contactIds = ref("");
const dialogTitle = ref("");
const dialogType = ref("");
const formRules = reactive({
  content: [
    {required: true, message: "请输入内容", trigger: ["change", "blur"]}
  ],
  substituteWord: [
    {required: true, message: "请输入替换词", trigger: ["change", "blur"]}
  ],
  state: [
    {required: true, message: "请选择状态", trigger: ["change", "blur"]}
  ],
});
const formSchema = computed(() => {
  return [
    {
      label: '内容',
      prop: 'content',
      component: 'el-input',
      colProps: {
        span: 24
      },
      props: {
        placeholder: '请输入内容',
        clearable: true,
      }
    },
    {
      label: '替换词',
      prop: 'substituteWord',
      component: 'el-input',
      colProps: {
        span: 24
      },
      props: {
        placeholder: '请输入替换词',
        clearable: true,
      }
    },
    {
      label: '状态',
      prop: 'state',
      component: shallowRef(fvSelect),
      colProps: {
        span: 24
      },
      props: {
        placeholder: '请选择状态',
        cacheKey: 'verbal_trick_state',
        clearable: true,
        filterable: true,
      }
    },
  ]
})
const searchConfig = reactive([
  {
    label: '内容',
    prop: 'content',
    props: {
      placeholder: '请输入内容查询',
      clearable: true,
      checkStrictly: true
    },
    component: 'el-input',
  },
  {
    label: '替换词',
    prop: 'substituteWord',
    props: {
      placeholder: '请输入替换词查询',
      clearable: true,
      checkStrictly: true
    },
    component: 'el-input',
  },
  {
    label: '状态',
    prop: 'state',
    props: {
      placeholder: '请选择状态查询',
      cacheKey: 'verbal_trick_state',
      clearable: true,
      filterable: true,
    },
    component: shallowRef(fvSelect),
  },
])
const sensitiveTableConfig= reactive({
  columns: [
    {
      type: 'selection',
      prop: 'selection'
    },
    {
      prop: 'index',
      type: 'index',
      label: '序号',
      align: 'center',
      width: 80,
    },
    {
      prop: 'sensitiveId',
      label: '敏感词ID',
      align: 'center'
    },
    {
      prop: 'content',
      label: '内容',
      align: 'center'
    },
    {
      prop: 'substituteWord',
      label: '替换词',
      align: 'center'
    },
    {
      prop: 'createTime',
      label: '创建时间',
      align: 'center'
    },
    {
      prop: 'state',
      label: '状态',
      align: 'center',
      showOverflowTooltip: false,
      currentRender: ({ row, index }) => {
        if (row.state !== null) {
          return (<Tag dictType={'verbal_trick_state'} value={row.state} />)
        } else {
          return '--'
        }
      }
    },
    {
      prop: 'oper',
      label: '操作',
      align: 'center',
      fixed: 'right',
      width: 150,
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        let btn = []
        btn.push({label: '编辑', func: () => handleEdit(row), type: 'primary'})
        btn.push({label: '删除', func: () => handleSingleDelete(row), type: 'danger'})
        return (
            <div style={{width: '100%'}}>
              {
                btn.map(item => (
                    <el-button
                        type={item.type}
                        // v-perm={item.prem}
                        onClick={() => item.func()}
                        link
                    >
                      {item.label}
                    </el-button>
                ))
              }
            </div>
        )
      }
    }

  ],
  api: '/sensitive/list',
  params: {},
  btns: [
    {name: '新增', key: 'add',type:'primary',icon:'Plus'},
    {name: '删除', key: 'delete', type: 'danger'},
  ]
})
const searchSensitive = (val) => {
  let obj = {...val}
  if (obj.dateValue) {
    obj.startTime = obj.dateValue[0]
    obj.endTime = obj.dateValue[1]
    delete obj.dateValue
  }
  sensitiveTableConfig.params = obj
  tableIns.value.refresh()
}

const headBtnClick = (key) => {
  switch (key) {
    case 'add':
      handleAdd()
      break;
    case 'delete':
      handleMoreDelete()
      break;
  }
}

const handleAdd = () => {
  formDialogRef.value.openOrCloseDialog(true)
  dialogTitle.value = "新增敏感词";
  dialogType.value = "add";
  nextTick(() => {
    formDialogRef.value.getFormInstance().setValues({})
    // 清空校验
    formDialogRef.value.getFormInstance().clearValidate()
    formDialogRef.value.getFormInstance().resetFields()
  })
}
const handleEdit = (row) => {
  formDialogRef.value.openOrCloseDialog(true)
  getDetail(row)
  dialogTitle.value = "编辑敏感词";
  dialogType.value = "edit";
}
const getDetail = (row) => {
  getSensitiveDetail(row.sensitiveId).then(res => {
    if (res.code === 1000) {
      ElMessage.success(res.msg)
      nextTick(() => {
        formDialogRef.value.getFormInstance().setValues(res.data)
        // 清空校验
        formDialogRef.value.getFormInstance().clearValidate()
      })
    } else {
    }
  })
}

const selectionChange = (selection) => {
  if (selection.length !== 0) {
    contactIds.value = selection.map(item => item.sensitiveId).join()
  } else {
    contactIds.value=''
  }
}
const deleteContactMethod = (sensitiveId) => {
  deleteSensitive(sensitiveId).then(res => {
    if (res.code === 1000) {
      ElMessage.success(res.msg)
      tableIns.value.refresh()
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const handleMoreDelete = () => {
  if(contactIds.value){
    ElMessageBox.confirm(`确认删除选择的敏感词吗?`, '系统提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteContactMethod(contactIds.value)
    })
  }else{
    ElMessage.warning("请选择要删除的敏感词")
  }
}
const handleSingleDelete = (row) => {
  ElMessageBox.confirm(`确认删除内容为${row.content}的敏感词吗?`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteContactMethod(row.sensitiveId)
  })
}

//提交
const handleSubmitAddressBook = async (formInstance) => {
  if (!formInstance) return;
  let validate = await formInstance.validate()
  if (!validate.isValidate) return;
  if (dialogType.value === "add") {
    addSensitive(formInstance.getValues()).then(res => {
      if (res.code === 1000) {
        ElMessage.success(res.msg);
        tableIns.value.refresh()
        formDialogRef.value.openOrCloseDialog(false)
      } else {
        ElMessage.error(res.msg);
      }
    });
  } else {
    editSensitive(formInstance.getValues()).then(res => {
      if (res.code === 1000) {
        ElMessage.success(res.msg);
        tableIns.value.refresh()
        formDialogRef.value.openOrCloseDialog(false)
      } else {
        ElMessage.error(res.msg);
      }
    });
  }
}
</script>

<style scoped>

</style>
