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

<script setup lang="jsx">
import fvSelect from '@/fvcomponents/fvSelect/index.vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {addVerbal, editVerbal,deleteVerbal, getVerbalDetail} from "@/api/verbal-trick";
import {reactive} from "vue";
const router = useRouter()
const dialogTitle = ref("");
const dialogType = ref("");
const verbalIds = ref("");
const formDialogRef = ref()
const tableIns = ref()
const searchConfig = reactive([
  {
    label: '知识内容',
    prop: 'query',
    props: {
      placeholder: '请输入知识内容查询',
      clearable: true,
      checkStrictly: true
    },
    component: 'el-input',
  },
  {
    label: '期望回复',
    prop: 'answer',
    props: {
      placeholder: '请输入期望回复查询',
      clearable: true,
      checkStrictly: true
    },
    component: 'el-input',
  },
  // {
  //   label: '是否挂断电话',
  //   prop: 'callOff',
  //   props: {
  //     placeholder: '请选择是否挂断电话查询',
  //     cacheKey: 'call_off',
  //     clearable: true,
  //     filterable: true,
  //   },
  //   component: shallowRef(fvSelect),
  // },
  // {
  //   label: '上下文类型',
  //   prop: 'type',
  //   props: {
  //     placeholder: '请选择上下文类型查询',
  //     cacheKey: 'context_type',
  //     clearable: true,
  //     filterable: true,
  //   },
  //   component: shallowRef(fvSelect),
  // },
])
const auths = reactive({
  add: ['order:verbal:add'],
  edit: ['order:verbal:edit'],
  delete: ['order:verbal:del'],
})
const verbalTrickTableConfig = reactive({
  columns: [
    {
      type: 'selection',
      prop: 'selection'
    },
    {
      prop: 'index',
      type: 'index',
      label: '序号',
      align: 'center',
      width: 80,
    },
    {
      prop: 'query',
      label: '知识内容',
      align: 'center'
    },
    {
      prop: 'answer',
      label: '期望回复',
      align: 'center'
    },
    // {
    //   prop: 'verbalContent',
    //   label: '内容',
    //   align: 'center'
    // },
    {
      prop: 'callOff',
      label: '是否挂断电话',
      align: 'center',
      width: '120',
      currentRender: ({ row, index }) => {
        if (row.callOff !== null) {
          return (<Tag dictType={'call_off'} value={row.callOff} />)
        } else {
          return '--'
        }
      }
    },
    {
      prop: 'type',
      label: '上下文类型',
      align: 'center',
      width: '120',
      currentRender: ({ row, index }) => {
        if (row.type !== null) {
          return (<Tag dictType={'context_type'} value={row.type} />)
        } else {
          return '--'
        }
      }
    },
    // {
    //   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: '编辑', prem: auths.edit, func: () => handleEdit(row), type: 'primary'})
        btn.push({label: '删除', prem: auths.delete, 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: '/verbal/list',
  params: {},
  btns: [
    {name: '新增', key: 'add',type:'primary',icon:'Plus', auth: auths.add},
    {name: '删除', key: 'delete', type: 'danger', auth: auths.delete},
  ]
})
const formRules = reactive({
  query: [
    {required: true, message: "请输入知识内容", trigger: ["change", "blur"]}
  ],
  // answer: [
  //   {required: true, message: "请输入期望回复", trigger: ["change", "blur"]}
  // ],
  callOff: [
    {required: true, message: "请选择是否挂断电话", trigger: ["change", "blur"]}
  ],
  // state: [
  //   {required: true, message: "请选择状态", trigger: ["change", "blur"]}
  // ],
});
const formSchema = computed(() => {
  return [
    {
      label: '知识内容',
      prop: 'query',
      component: 'el-input',
      colProps: {
        span: 24
      },
      props: {
        placeholder: '请输入知识内容',
        clearable: true,
        type:'textarea',
        rows:3
      }
    },
    {
      label: '期望回复',
      prop: 'answer',
      component: 'el-input',
      colProps: {
        span: 24
      },
      props: {
        placeholder: '请输入期望回复',
        clearable: true,
        type:'textarea',
        rows:3
      }
    },
    {
      label: '是否挂断电话',
      prop: 'callOff',
      component: shallowRef(fvSelect),
      colProps: {
        span: 24
      },
      props: {
        placeholder: '请选择是否挂断电话',
        cacheKey: 'call_off',
        clearable: true,
        filterable: true,
      }
    },
    {
      label: '上下文类型',
      prop: 'type',
      component: shallowRef(fvSelect),
      colProps: {
        span: 24
      },
      props: {
        placeholder: '请选择上下文类型',
        cacheKey: 'context_type',
        clearable: true,
        filterable: true,
      }
    },
  ]
})
const searchVerbalTrick = (val) => {
  let obj = {...val}
  if (obj.dateValue) {
    obj.startTime = obj.dateValue[0]
    obj.endTime = obj.dateValue[1]
    delete obj.dateValue
  }
  verbalTrickTableConfig.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) => {
  getVerbalDetail(row.templateId).then(res => {
    if (res.code === 1000) {
      res.data.callOff=res.data.callOff+''
      nextTick(() => {
        formDialogRef.value.getFormInstance().setValues(res.data)
        // 清空校验
        formDialogRef.value.getFormInstance().clearValidate()
      })
    } else {
      ElMessage.warning(res.msg)
    }
  })
}

const selectionChange = (selection) => {
  if (selection.length !== 0) {
    verbalIds.value = selection.map(item => item.templateId).join()
  } else {
    verbalIds.value=''
  }
}
const deleteContactMethod = (verbalId) => {
  deleteVerbal(verbalId).then(res => {
    if (res.code === 1000) {
      ElMessage.success(res.msg)
      tableIns.value.refresh()
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const handleMoreDelete = () => {
  if(verbalIds.value){
    ElMessageBox.confirm(`确认删除选择的话术吗?`, '系统提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteContactMethod(verbalIds.value)
    })
  }else{
    ElMessage.warning("请选择要删除的话术")
  }
}
const handleSingleDelete = (row) => {
  ElMessageBox.confirm(`确认删除问题为${row.query}的话术吗?`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteContactMethod(row.templateId)
  })
}

//提交
const handleSubmitVerbalTrick = async (formInstance) => {
  if (!formInstance) return;
  let validate = await formInstance.validate()
  if (!validate.isValidate) return;
  if (dialogType.value === "add") {
    addVerbal(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 {
    editVerbal(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>
