<template>
  <fvSearchForm :searchConfig="searchConfig" @search="searchPhoneTraffic"></fvSearchForm>
  <fvTable ref="tableIns" :tableConfig="phoneTrafficTableConfig"  @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 {addConfig, delConfig, editConfig, getConfigDetails} from "@/api/phone-traffic-config";
const router = useRouter()
const tableIns = ref()
const formDialogRef = ref()
const extraConfigType = ref(0)
const contactIds = ref("");
const dialogTitle = ref("");
const dialogType = ref("");
const formRules = reactive({
  configName: [
    {required: true, message: "参数名称不能为空", trigger: "blur"},
  ],
  configKey: [
    {required: true, message: "参数键名不能为空", trigger: "blur"},
  ],
  configValue: [
    {required: true, message: "参数键值不能为空", trigger: "blur"},
  ],
  configType: [
    {required: true, message: "系统内置不能为空", trigger: "change"},
  ],
});
const formSchema = computed(() => {
  return [
    {
      label: '参数名称',
      prop: 'configName',
      component: 'el-input',
      colProps: {
        span: 24
      },
      props: {
        placeholder: '请输入参数名称',
        clearable: true,
      }
    },
    {
      label: '参数键名',
      prop: 'configKey',
      component: 'el-input',
      colProps: {
        span: 24
      },
      props: {
        placeholder: '请输入参数键名',
        clearable: true,
      }
    },
    {
      label: '参数键值',
      prop: 'configValue',
      component: 'el-input',
      colProps: {
        span: 24
      },
      props: {
        placeholder: '请输入参数键值',
        clearable: true,
      }
    },
    {
      label: '系统内置',
      prop: 'configType',
      component: shallowRef(fvSelect),
      colProps: {
        span: 24
      },
      props: {
        placeholder: '请选择系统内置',
        cacheKey: 'yes_no',
        clearable: true,
        filterable: true,
      }
    },
    {
      label: '备注',
      prop: 'remark',
      component: 'el-input',
      colProps: {
        span: 24
      },
      props: {
        placeholder: '请输入备注',
        clearable: true,
      },
    }
  ]
})
const searchConfig = reactive([
  {
    label: '参数名称',
    prop: 'configName',
    props: {
      placeholder: '请输入参数名称查询',
      clearable: true,
      checkStrictly: true
    },
    component: 'el-input',
  },
  {
    label: '参数键名',
    prop: 'configKey',
    props: {
      placeholder: '请输入参数键名查询',
      clearable: true,
      checkStrictly: true
    },
    component: 'el-input',
  },
  {
    label: '系统内置',
    prop: 'configType',
    props: {
      placeholder: '请选择系统内置查询',
      cacheKey: 'yes_no',
      clearable: true,
      filterable: true,
    },
    component: shallowRef(fvSelect),
  }
])
const phoneTrafficTableConfig = reactive({
  columns: [
    {
      type: 'selection',
      prop: 'selection'
    },
    {
      prop: 'index',
      type: 'index',
      label: '序号',
      align: 'center',
      width: 80,
    },
    {
      prop: 'configName',
      label: '参数名称',
      align: 'center'
    },
    {
      prop: 'configKey',
      label: '参数键名',
      align: 'center'
    },
    {
      prop: 'configValue',
      label: '参数键值',
      align: 'center'
    },
    {
      prop: 'configType',
      label: '系统内置',
      align: 'center',
      currentRender: ({ row, index }) => {
        if (row.configType !== null) {
          return (<Tag dictType={'yes_no'} value={row.configType} />)
        } else {
          return '--'
        }
      }
    },
    // {
    //   prop: 'workOrderTime',
    //   label: '创建时间',
    //   align: 'center',
    //   width: 200
    // },
    {
      prop: 'remark',
      label: '备注',
      align: 'center',
    },
    {
      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: '/extra/config',
  params: {
    extraConfigType:extraConfigType.value
  },
  btns: [
    {name: '新增', key: 'add',type:'primary'},
    {name: '删除', key: 'delete', type: 'danger'},
  ]
})
const searchPhoneTraffic = (val) => {
  let obj = {...val,extraConfigType:extraConfigType.value}
  if (obj.dateValue) {
    obj.startTime = obj.dateValue[0]
    obj.endTime = obj.dateValue[1]
    delete obj.dateValue
  }
  phoneTrafficTableConfig.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) => {
  getConfigDetails(row.configId,extraConfigType.value).then(res => {
    if (res.code === 1000) {
      ElMessage.success(res.msg)
      res.data.configType=''+res.data.configType
      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.configId).join()
  } else {
    contactIds.value=''
  }
}
const deleteContactMethod = (configId) => {
  delConfig(configId,extraConfigType.value).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.configName}的话务配置吗?`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteContactMethod(row.configId)
  })
}

//提交
const handleSubmitAddressBook = async (formInstance) => {
  if (!formInstance) return;
  let validate = await formInstance.validate()
  if (!validate.isValidate) return;
  let params={
    ...formInstance.getValues(),
    configType:parseInt(formInstance.getValues().configType),
    extraConfigType:extraConfigType.value
  }
  if (dialogType.value === "add") {
    addConfig(params).then(res => {
      if (res.code === 1000) {
        ElMessage.success(res.msg);
        tableIns.value.refresh()
        formDialogRef.value.openOrCloseDialog(false)
      } else {
        ElMessage.error(res.msg);
      }
    });
  } else {
    editConfig(params).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>
