<template>
  <div>
    <TableProMax
        ref="tableRef"
        :request-api="reqApi"
        :columns="columns"
        :searchFormOptions="searchFormOptions"
        :scroll="{x}"
    >
      <template #tableHeader>
        <a-space>
          <a-button type="primary" @click="addServiceProjects">新增服务项目</a-button>
        </a-space>
      </template>
    </TableProMax>
    <a-modal
        v-model:open="visible"
        :title="serviceTitle"
        @ok="submit"
        @cancel="closeModal"
    >
      <FormProMax ref="formRef"  v-model:value="formParams" :form-item-options="formItemOptions"/>
    </a-modal>
  </div>

</template>

<script setup lang="tsx">
import TableProMax from "@/components/table/TableProMax.vue";
import {TableProMaxProps} from "@/types/components/table";
import api from "@/axios";
import {onMounted, ref} from "vue";
import {ComponentExposed} from "vue-component-type-helpers";
import {dictSelectNodes} from "@/config/dict.ts";
import {serviceProjectSaveOrUpdateParams} from "@/types/views/serviceManagement.ts";
import {FormExpose} from "ant-design-vue/es/form/Form";
import {FormProMaxItemOptions} from "@/types/components/form";
import FormProMax from "@/components/form/FormProMax.vue";
import {message} from "ant-design-vue";

type TableProps = TableProMaxProps<serviceProjectSaveOrUpdateParams>  //需要修改

const tableRef = ref<ComponentExposed<typeof TableProMax>>(null!)
// table表格
const reqApi: TableProps['requestApi'] = (params) => api.post('/serviceProject/pager', params)  //分页


const searchFormOptions: TableProps["searchFormOptions"] = {
  name: {
    type: 'input',
    label: '服务项目名称'
  },
  projectManagerMiniProgramUserName:{
    type: 'input',
    label: '服务经理用户名称'
  },
  remark: {
    type: 'input',
    label: '备注'
  },
  type: {
    type: 'select',
    label: '服务项目类型',
    options: [
      {
        value: null,
        label: '全部'
      },...dictSelectNodes('ServiceProjectType')
    ]
  }
}
const visible = ref(false)
const serviceTitle = ref('新增服务项目')
const formRef = ref<FormExpose>(null)
const formParams = ref<{
  snowFlakeId?: string,
  enterprisesUnitId:string,
  administrativeDivisionCodes?:null,
  projectManagerMiniProgramUserId?:string,
  name: string,
  type:string,
  isRecruitSecurity:number,
  idNumber?: string,
  serviceArea?:number,
  buildingTotal?:number,
  houseTotal?:number,
  staffTotal?:number,
  securityUserTotal?:number
  remark?: string,
}>({
  name:'',
  isRecruitSecurity:0,
  enterprisesUnitId:null,
  type:'property'
})

const columns: TableProps['columns'] = [
  {
    dataIndex: 'enterprisesUnitName',
    title: '企事业单位名称',
    width: 150,
    ellipsis: true
  },
  {
    dataIndex: 'projectManagerMiniProgramUserName',
    title: '项目经理小程序用户名称',
    width: 200,
    ellipsis: true
  }, {
    dataIndex: 'name',
    title: '服务项目名称',
    width: 150,
    ellipsis: true
  },
  {
    dataIndex:'type',
    title: '服务类型',
    customRender: ({text}) => <a-tag>{text?.label}</a-tag>,
    width:100
  },
  {
    dataIndex:'isRecruitSecurity',
    title: '是否自招保安',
    customRender: ({text}) => <a-tag>{text?.label}</a-tag>,
    width:100
  },
  {
    dataIndex:'idNumber',
    title: '证件号',
    width:200
  },
  {
    dataIndex:'serviceArea',
    title:'服务区域面积',
    width:100
  },
  {
    dataIndex:'buildingTotal',
    title:'楼栋数量',
    width:100
  },
  {
    dataIndex:'houseTotal',
    title:'户数',
    width:100
  },
  {
    dataIndex:'staffTotal',
    title:'工作人员数量',
    width:100
  },
  {
    dataIndex:'securityUserTotal',
    title:'保安人员数量',
    width:100
  },
  {
    dataIndex:'createUserName',
    title:'创建人名称',
    width:100
  },
  {
    dataIndex: 'createTime',
    title: '创建时间',
    width: 100,
    ellipsis: true,
  },
  {
    dataIndex: 'remark',
    title: '备注',
    width: 200,
    ellipsis: true
  },{
    dataIndex: 'opt',
    title: '操作',
    fixed: "right",
    width:200,
    customRender({record}){
      return <a-space>
        <a-popconfirm
            title="确认删除账号吗?"
            onConfirm={async () => {
              const resp = await api.delete('/serviceProject/deleteById', {
                serviceProjectId: record.snowFlakeId,
              })
              message.success(resp.message)
              await tableRef.value?.requestGetTableData()
            }}>
          <a-button type="primary" danger>删除</a-button>
        </a-popconfirm>
        <a-button type="primary" onClick={ async ()=>{
          console.log(record)
          visible.value = true
          serviceTitle.value = '编辑服务项目'
          if(record.isRecruitSecurity === null ){
            idNumberDisabled.value = false
          }
          if(record.type.value === 'security'){
            isRecruitSecurityHidden.value = true
            formParams.value.isRecruitSecurity = null
          }else{
            formParams.value.isRecruitSecurity = record.isRecruitSecurity.value
            if(record.isRecruitSecurity.value === 1){
              idNumberDisabled.value = true
            }
          }
          formParams.value.snowFlakeId = record.snowFlakeId
          formParams.value.name = record.name
          formParams.value.type = record.type.value
          formParams.value.remark = record.remark
          formParams.value.idNumber = record.idNumber
          formParams.value.serviceArea = record.serviceArea
          formParams.value.buildingTotal = record.buildingTotal
          formParams.value.houseTotal = record.houseTotal
          formParams.value.staffTotal =  record.staffTotal
          formParams.value. securityUserTotal = record.securityUserTotal

          formParams.value.enterprisesUnitId = record.enterprisesUnitName
          enterprisesUnitId.value = record.enterprisesUnitId
          formParams.value.administrativeDivisionCodes = record.enterprisesUnitAdministrativeDivisionCodes
        }}>编辑</a-button>
      </a-space>
    }
  },
]
const x: number = columns.reduce((a, b) => a + (b.width as number), 0)


const administrativeDivisionTree = ref<TreeNodeVo<string>[]>([])  //行政区划
const getAdministrativeDivisionTree = async ()=>{
  const resp =  await api.get<TreeNodeVo<string>[]>('/common/administrativeDivisionTree')
  administrativeDivisionTree.value = resp.data as TreeNodeVo<string>[]
}

// 企事业单位接口
const enterprisesUnitIdList = ref<SelectNodeVo<string>[]>([])
const enterprisesUnitId = ref('')
const isRecruitSecurityHidden = ref<boolean>(false)

const idNumberDisabled = ref<boolean>(false)
const formItemOptions = ref<FormProMaxItemOptions<serviceProjectSaveOrUpdateParams>>({
  name: {
    type: 'input',
    label: '名称',
    required: true,
  },
  administrativeDivisionCodes:{
    type:'cascader',
    label:'行政区划',
    required: true,
    options: administrativeDivisionTree,
    componentsProps:{
      showSearch:true,
      onChange: async (values)=>{
       const resp = await  api.post<SelectNodeVo<string>[]>('/enterprisesUnit/queryListByAdministrativeDivisionCodes',values)
        enterprisesUnitIdList.value = resp.data
      }
    }
  },
  enterprisesUnitId:{
     type:'select',
     label:'企事业单位',
     options:enterprisesUnitIdList,
     componentsProps:{
      allowClear:true
    }
  },
  type: {
    type: 'radioGroup',
    label: '服务类型',
    options: dictSelectNodes('ServiceProjectType'),
    required: true,
    componentsProps:{
       onChange:(e)=>{
         if(e.target.value === 'security'){
           isRecruitSecurityHidden.value = true
           formParams.value.isRecruitSecurity = null
           idNumberDisabled.value = false
         }else{
           formParams.value.isRecruitSecurity = 0
           isRecruitSecurityHidden.value = false
         }
       }
    }
  },
  isRecruitSecurity: {
    type: 'radioGroup',
    label: '是否自招保安',
    options:dictSelectNodes('IsOrNot'),
    hidden:isRecruitSecurityHidden as any,
    componentsProps:{
       onChange:(e)=>{
         idNumberDisabled.value = e.target.value !== 0;
        formParams.value.idNumber = ''
       }
    }
  },
  idNumber: {
    type: 'input',
    label: '证件号',
    componentsProps:{
       disabled:idNumberDisabled as any
    }
  },
  serviceArea:{
    type:'inputNumber',
    label:'服务区域面积',

  },
  buildingTotal:{
     type:'inputNumber',
     label:'楼栋数量',
    componentsProps:{
      formatter:(value:any)=>{
        return Math.round(value)?Math.round(value):''  as any
      },
      min:0
    }
  },
  houseTotal:{
    type:'inputNumber',
     label:'户数',
    componentsProps:{
      formatter:(value:any)=>{
        return Math.round(value)?Math.round(value):''  as any
      },
      min:0
    }
  },
  staffTotal:{
    type:'inputNumber',
    label:'工作人员数量',
    componentsProps:{
      formatter:(value:any)=>{
        return Math.round(value)?Math.round(value):''  as any
      },
      min:0
    }
  },
  securityUserTotal:{
    type:'inputNumber',
    label:'保安人员数量',
    componentsProps:{
      formatter:(value:any)=>{
        return Math.round(value)?Math.round(value):''  as any
      },
      min:0
    }
  },
  remark: {
    type: 'inputTextArea',
    label: '备注',
  }
})
const submit = async()=>{
  await formRef.value.validate()
  const snowFlakeId = ref('')
  const UnitId = ref('')
  if (serviceTitle.value === '新增服务项目') {
    snowFlakeId.value = ''
    UnitId.value = formParams.value.enterprisesUnitId
  } else {
    snowFlakeId.value = formParams.value.snowFlakeId
    UnitId.value = enterprisesUnitId.value
  }
  const serviceProjectSaveOrUpdateParams = {
    snowFlakeId: snowFlakeId.value,
    enterprisesUnitId:UnitId.value,
    name: formParams.value.name,
    type:formParams.value.type,
    isRecruitSecurity:formParams.value.isRecruitSecurity,
    idNumber: formParams.value.idNumber,
    serviceArea:formParams.value.serviceArea,
    buildingTotal:formParams.value.buildingTotal,
    houseTotal:formParams.value.houseTotal,
    staffTotal:formParams.value.staffTotal,
    securityUserTotal:formParams.value.securityUserTotal,
    remark: formParams.value.remark,
  }
  const resp = await  api.post('/serviceProject/saveOrUpdate',serviceProjectSaveOrUpdateParams)
  message.success(resp.message)
  await tableRef.value?.requestGetTableData()
  await closeModal()

}
const closeModal = async()=>{
    visible.value = false
    formParams.value = {
       enterprisesUnitId:'',
       administrativeDivisionCodes:'',
       name:'',
       type:'property',
       isRecruitSecurity:0,
       idNumber:'',
       serviceArea:null,
       buildingTotal:null,
       houseTotal:null,
       staffTotal:null,
       securityUserTotal:null,
       remark:''
   }
    // await formRef.value.resetFields()
    enterprisesUnitId.value = ''
    serviceTitle.value = '新增服务项目'
    isRecruitSecurityHidden.value = false
    idNumberDisabled.value = false
}
const addServiceProjects = () => {
  visible.value = true
}

onMounted(async ()=>{
  await getAdministrativeDivisionTree()
})
</script>


<style scoped lang="scss">

</style>
