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

<script setup lang="jsx">
import fvSelect from '@/fvcomponents/fvSelect/index.vue'
import {addContact, editContact, getContactDetail, deleteContact} from "@/api/address-book";
import {ElMessage, ElMessageBox} from "element-plus";

const router = useRouter()
const tableIns = ref()
const formDialogRef = ref()
const delBtnDisabled = ref(true)
const contactIds = ref("");
const dialogTitle = ref("");
const dialogType = ref("");
const formRules = reactive({
  siteName: [
    {required: true, message: "请输入电站", trigger: ["change", "blur"]}
  ],
  role: [
    {required: true, message: "请选择角色", trigger: ["change", "blur"]}
  ],
  name: [
    {required: true, message: "请输入姓名", trigger: ["change", "blur"]}
  ],
  phone: [
    {required: true, message: "请输入手机号", trigger: ["change", "blur"]}
  ]
});
const formSchema = computed(() => {
  return [
    {
      label: '电站',
      prop: 'siteName',
      component: 'el-input',
      colProps: {
        span: 24
      },
      props: {
        placeholder: '请输入电站',
        clearable: true,
      }
    },
    {
      label: '角色',
      prop: 'role',
      component: shallowRef(fvSelect),
      colProps: {
        span: 24
      },
      props: {
        placeholder: '请选择角色',
        cacheKey: 'address_book_role',
        clearable: true,
        filterable: true,
      }
    },
    {
      label: '姓名',
      prop: 'name',
      component: 'el-input',
      colProps: {
        span: 24
      },
      props: {
        placeholder: '请输入姓名',
        clearable: true,
      }
    },
    {
      label: '手机号',
      prop: 'phone',
      component: 'el-input',
      colProps: {
        span: 24
      },
      props: {
        placeholder: '请输入手机号',
        clearable: true,
      },
    },
    {
      label: '规则',
      prop: 'rule',
      component: 'el-input',
      colProps: {
        span: 24
      },
      props: {
        placeholder: '请输入规则',
        clearable: true,
      },
    }
  ]
})
const searchConfig = reactive([
  {
    label: '电站',
    prop: 'siteName',
    props: {
      placeholder: '请输入电站查询',
      clearable: true,
      checkStrictly: true
    },
    component: 'el-input',
  },
  {
    label: '角色',
    prop: 'role',
    component: shallowRef(fvSelect),
    props: {
      placeholder: '请选择角色查询',
      cacheKey: 'address_book_role',
      clearable: true,
      filterable: true,
    },
  },
  {
    label: '姓名',
    prop: 'name',
    props: {
      placeholder: '请输入姓名查询',
      clearable: true,
      checkStrictly: true
    },
    component: 'el-input',
  }
])
const tableConfig = reactive({
  columns: [
    {
      type: 'selection',
      prop: 'selection'
    },
    {
      prop: 'index',
      type: 'index',
      label: '序号',
      align: 'center',
      width: 80,
    },
    {
      prop: 'siteName',
      label: '电站',
      align: 'center'
    },
    {//0：运维；1：地面调度；2：现场调度
      prop: 'role',
      label: '角色',
      align: 'center',
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        if (row.role !== null) {
          return (<Tag dictType={'address_book_role'} value={row.role}/>)
        } else {
          return '--'
        }
      }
    },
    {
      prop: 'name',
      label: '姓名',
      align: 'center'
    },
    {
      prop: 'phone',
      label: '手机号',
      align: 'center'
    },
    {
      prop: 'rule',
      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: '/contact/list',
  params: {},
  btns: [
    {name: '新增', key: 'add', type: 'primary'},
    {name: '删除', key: 'delete', type: 'danger'},
  ]
})
const search = (val) => {
  let obj = {...val}
  if (obj.dateValue) {
    obj.startTime = obj.dateValue[0]
    obj.endTime = obj.dateValue[1]
    delete obj.dateValue
  }
  tableConfig.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().clearValidate()
    formDialogRef.value.getFormInstance().resetFields()
  })
}
const handleEdit = (row) => {
  formDialogRef.value.openOrCloseDialog(true)
  getDetail(row)
  dialogTitle.value = "编辑通讯录";
  dialogType.value = "edit";
}
const getDetail = (row) => {
  getContactDetail(row.contactsId).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) {
    delBtnDisabled.value = false
    contactIds.value = selection.map(item => item.contactsId).join()
  } else {
    contactIds.value=''
    delBtnDisabled.value = true
  }
}
const deleteContactMethod = (contactsId) => {
  deleteContact(contactsId).then(res => {
    if (res.code === 1000) {
      ElMessage.success(res.msg)
      tableIns.value.refresh()
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const handleMoreDelete = () => {
  console.info("🚀 ~method:contactIds -----", contactIds.value)

    if(contactIds.value){
      ElMessageBox.confirm(`确认删除选择的通讯录吗?`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      deleteContactMethod(contactIds.value)
      })
    }else{
      ElMessage.warning("请选择要删除的通讯录")
    }

}
const handleSingleDelete = (row) => {
  ElMessageBox.confirm(`确认删除姓名为${row.name}的通讯录吗?`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteContactMethod(row.contactsId)
  })
}

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