<template>
  <div class="address-book">
    <fvSearchForm :searchConfig="searchConfig" @search="searchAddressBook"></fvSearchForm>
    <div style="display: flex;">
      <el-button type="primary" v-perm="auths.add" @click="handleAdd">新增</el-button>
      <import-excel @success="importAddress"/>
      <el-button type="info" v-perm="auths.export" @click="handleExport">导出</el-button>
      <el-button type="danger" v-perm="auths.delete" @click="handleMoreDelete">删除</el-button>
    </div>
<!--    @headBtnClick="headBtnClick"-->
      <fvTable ref="tableIns" :tableConfig="addressBookTableConfig"
               @selectionChange="selectionChange"></fvTable>
      <fvFormDialog ref="formDialogRef" :title="dialogTitle" :dialogType="dialogType"
                    :form-schema="formSchema" :form-rules="formRules"
                    @dialogSubmit="handleSubmitAddressBook"></fvFormDialog>
    </div>
</template>

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

const router = useRouter()
const tableIns = ref()
const formDialogRef = ref()
const contactIds = ref("");
const dialogTitle = ref("");
const dialogType = ref("");


// 手机号验证
const checkPhone = (rule, value, callback) => {
  // const phoneReg = /^1[3|4|5|6|7|8][0-9]{9}$/
  const phoneReg = /^\d{11}$/
  setTimeout(() => {
    if (!Number.isInteger(+value)) {
      callback(new Error('请输入数字值'))
    } else {
      if (phoneReg.test(value)) {
        callback()
      } else {
        callback(new Error('手机号码长度不足11位，如果是座机，请添加区号'))
      }
    }
  }, 100)
};
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"]},
    {validator: checkPhone, 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: 'dispatchUnit',
      component: 'el-input',
      colProps: {
        span: 24
      },
      props: {
        placeholder: '请输入拨打单位',
        clearable: true,
      }
    },
    {
      label: '班组信息',
      prop: 'team',
      component: 'el-input',
      colProps: {
        span: 24
      },
      props: {
        placeholder: '请输入班组信息',
        clearable: 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,
        controls: false
      },
    },
    {
      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 auths = reactive({
  add: ['order:contacts:add'],
  edit: ['order:contacts:edit'],
  import: ['order:contacts:import'],
  export: ['order:contacts:export'],
  delete: ['order:contacts:del'],
})
const addressBookTableConfig = 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: 'dispatchUnit',
      label: '拨打单位',
      align: 'center'
    },
    {
      prop: 'team',
      label: '班组信息',
      align: 'center'
    },
    {
      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: '编辑', 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: '/contact/list',
  params: {},
  btns: [
    // {name: '新增', key: 'add', type: 'primary', auth: auths.add},
    // {name: '导入', key: 'import', type: 'warning', auth: auths.import},
    // {name: '导出', key: 'export', type: 'info', auth: auths.export},
    // {name: '删除', key: 'delete', type: 'danger', auth: auths.delete},
  ]
})
const searchAddressBook = (val) => {
  let obj = {...val}
  if (obj.dateValue) {
    obj.startTime = obj.dateValue[0]
    obj.endTime = obj.dateValue[1]
    delete obj.dateValue
  }
  addressBookTableConfig.params = obj
  tableIns.value.refresh()
}
const importAddress = () => {
  tableIns.value.refresh()
}
const headBtnClick = (key) => {
  switch (key) {
    case 'add':
      handleAdd()
      break;
    case 'import':
      handleImport()
      break;
    case 'export':
      handleExport()
      break;
    case 'delete':
      handleMoreDelete()
      break;
  }
}
//通讯录导入
const handleImport = () => {

}
//通讯录导出
const handleExport = () => {
  exportContact().then(res => {
    let link = document.createElement('a')
    try {
      let blob = new Blob([res.data], {type: 'application/vnd.ms-excel'});
      let _fileName = "运维智能语音服务系统-通讯录.xlsx"
      link.style.display = 'none';
      // 兼容不同浏览器的URL对象
      const url = window.URL || window.webkitURL || window.moxURL;
      link.href = url.createObjectURL(blob);
      link.setAttribute('download', _fileName.substring(_fileName.lastIndexOf('_') + 1))
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      url.revokeObjectURL(link.href);//销毁url对象
    } catch (e) {
      console.log('下载的文件出错', e)
    }
  })
}
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) => {
  getContactDetail(row.contactsId).then(res => {
    if (res.code === 1000) {
      nextTick(() => {
        formDialogRef.value.getFormInstance().setValues(res.data)
        // 清空校验
        formDialogRef.value.getFormInstance().clearValidate()
      })
    } else {
      ElMessage.success(res.msg)
    }
  })
}

const selectionChange = (selection) => {
  if (selection.length !== 0) {
    contactIds.value = selection.map(item => item.contactsId).join()
  } else {
    contactIds.value = ''
  }
}
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 = () => {
  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 handleSubmitAddressBook = async (formInstance) => {
  if (!formInstance) return;
  let validate = await formInstance.validate()
  if (!validate.isValidate) return;
  if (formInstance.getValues().role == '0' && !formInstance.getValues().team) {
    ElMessage.warning('请输入班组信息');
    return;
  }
  if (formInstance.getValues().role == '1' && !formInstance.getValues().dispatchUnit) {
    ElMessage.warning('请输入拨打单位');
    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 lang="scss">
.address-book {

  .el-input-number {
    width: 100% !important;

    .el-input__inner {
      text-align: left;
    }
  }
}
</style>
