<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">
      </FormProMax>
    </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 {computed, 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";
import SingleImageFileUpload from "@/components/upload/SingleImageFileUpload.vue";

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

const tableRef = ref<ComponentExposed<typeof TableProMax>>(null!)
// table表格
const reqApi: TableProps['requestApi'] = (params) => api.post('/m3/sp/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,
  projectManagerMiniProgramUserName?:string
  name: string,
  type:string,
  twoType?: number,
  outsourceName?:string,
  isFiling:number,
  idNumber?: string,
  securityServiceContract?:string,
  serviceArea?:number,
  buildingTotal?:number,
  houseTotal?:number,
  staffTotal?:number,
  securityUserTotal?:number
  remark?: string,
}>({
  name:'',
  enterprisesUnitId:null,
  type:'security',
  isFiling:0
})

const columns: TableProps['columns'] = [
  {
    dataIndex: 'name',
    title: '服务项目名称',
    width: 150,
    ellipsis: true
  },
  {
    dataIndex: 'projectManagerMiniProgramUserName',
    title: '项目经理小程序用户名称',
    width: 200,
    ellipsis: true
  },
  {
    dataIndex: 'enterprisesUnitName',
    title: '企事业单位名称',
    width: 150,
    ellipsis: true,
  },
  {
    dataIndex:'type',
    title: '服务类型',
    customRender: ({text}) => <a-tag>{text?.label}</a-tag>,
    width:100
  },
  {
    dataIndex:'twoType',
    title: '二级类型',
    customRender: ({text}) => <a-tag>{text?.label}</a-tag>,
    width:120
  },
  {
    dataIndex:'outsourceName',
    title: '外包公司名称',
    width:120
  },
  {
    dataIndex:'isFiling',
    title: '是否备案',
    customRender: ({text}) => <a-tag>{text?.label}</a-tag>,
    width:120
  },
  {
    dataIndex:'idNumber',
    title: '保安服务许可证',
    width:170
  },
  {
    dataIndex:'securityServiceContract',
    title:'保安服务合同',
    width:200,
    customRender({text}) {
      return <a-image width={100} height={100} src={__APP_ENV.VITE_APP_MINIO_URL + text}></a-image>
    },
    ellipsis: true,
  },
  {
    dataIndex:'serviceArea',
    title:'服务区域面积',
    width:120,
  },
  {
    dataIndex:'buildingTotal',
    title:'楼栋数量',
    width:100
  },
  {
    dataIndex:'houseTotal',
    title:'户数',
    width:100
  },
  {
    dataIndex:'staffTotal',
    title:'工作人员数量',
    width:120
  },
  {
    dataIndex:'securityUserTotal',
    title:'保安人员数量',
    width:120
  },
  {
    dataIndex:'createUserName',
    title:'创建人名称',
    width:110
  },
  {
    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('/m3/sp/del_id', {
                serviceProjectId: record.snowFlakeId,
              })
              message.success(resp.message)
              await tableRef.value?.requestGetTableData()
            }}>
          <a-button  danger>删除</a-button>
        </a-popconfirm>
        <a-button type="primary" onClick={ async ()=>{
          visible.value = true
          serviceTitle.value = '编辑服务项目'
          idNumberDisabled.value = record.twoType.value !== 'outsource';
          formParams.value.projectManagerMiniProgramUserId = record.projectManagerMiniProgramUserId
          formParams.value.snowFlakeId = record.snowFlakeId
          formParams.value.name = record.name
          formParams.value.type = record.type.value
          formParams.value.twoType = record.twoType.value
          formParams.value.outsourceName = record.outsourceName
          formParams.value.isFiling = record.isFiling.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
          formParams.value.administrativeDivisionCodes = record.enterprisesUnitAdministrativeDivisionCodes
          formParams.value.securityServiceContract = record.securityServiceContract

        }}>编辑</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/administrativeDivisionByParentCode',{parentCode:'0'})
  administrativeDivisionTree.value = resp.data as TreeNodeVo<string>[]
}

// 项目经理接口
const userNameOptions = ref([])
const projectManagerMiniProgram = async()=>{
  const resp = await api.get('/m3/list_p_m')
  userNameOptions.value = resp.data as any
}

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

const isRecruitSecurityHidden = ref<boolean>(false)
const idNumberDisabled = ref<boolean>(true)

// 切换options
const netType = computed(() => {
  return formParams.value.type === 'security' ? dictSelectNodes("ServiceProjectTwoType") : dictSelectNodes("UserType" as any)
})


const formItemOptions = ref<FormProMaxItemOptions<serviceProjectSaveOrUpdateParams>>({
  name: {
    type: 'input',
    label: '名称',
    required: true,
  },
  projectManagerMiniProgramUserId:{
      type:'select',
      label:'项目经理',
      options:userNameOptions,
  },
  administrativeDivisionCodes:{
    type:'administrativeDivisionsTree',
    label:'行政区划',
    required: true,
    componentsProps:{
      showSearch:true,
      onChange: async (values:any)=>{
          const resp = await  api.post<SelectNodeVo<string>[]>('/eu/list_ad_codes',values)
          enterprisesUnitIdList.value = resp.data
      },
    }
  },
  enterprisesUnitId:{
     type:'select',
     label:'企事业单位',
     required: true,
     options:enterprisesUnitIdList,
     componentsProps:{
       allowClear:true,
       showSearch:true,
       onChange:async (value:string)=>{
         console.log(value)
         enterprisesUnitId.value = value
       },
       filterOption:(input: string, option: any)=>{
         return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
       }
    }
  },
  type: {
    type: 'radioGroup',
    label: '服务类型',
    options: dictSelectNodes('ServiceProjectType'),
    required: true,
    componentsProps:{
       onChange:(e)=>{
         if(e.target?.value === 'security'){
           isRecruitSecurityHidden.value = false
           formParams.value.twoType = null
         }else{
           formParams.value.twoType = null
           isRecruitSecurityHidden.value = true
         }
       }
    }
  },
  twoType: {
    type: 'radioGroup',
    label: '二级类型',
    options:netType,
    required: true,
    componentsProps:{
       onChange:(e)=>{
         if(e.target.value !== "outsource"){
           idNumberDisabled.value = true
           formParams.value.outsourceName = ''
         }else{
           idNumberDisabled.value = false
         }
       },
    }
  },
  outsourceName:{
    type: 'input',
    label: '外包公司名称',
    hidden:idNumberDisabled as any,
  },
  isFiling:{
    type: 'radioGroup',
    label: '是否备案',
    required: true,
    options:dictSelectNodes('IsOrNot'),
  },
  idNumber: {
    type: 'input',
    label: '保安服务许可证',
  },
  securityServiceContract:{
    type:'custom',
    label: '保安服务合同',
    required: true,
    customRender: () =>
       <div>
         <SingleImageFileUpload height={200} v-model:value={formParams.value.securityServiceContract}  />
         <div class="securityServiceContract">注：（只需提供体现签订合同的单位和执行合同起止时间的页面即可）两张合在一起进行上传</div>
       </div>
   },
  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 UnitId = ref('')
const submit = async()=>{
  await formRef.value.validate()
  const snowFlakeId = 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,
    projectManagerMiniProgramUserId:formParams.value.projectManagerMiniProgramUserId,
    name: formParams.value.name,
    type:formParams.value.type,
    twoType: formParams.value.twoType,
    outsourceName:formParams.value.outsourceName,
    isFiling:formParams.value.isFiling,
    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,
    securityServiceContract:formParams.value.securityServiceContract
  }
  const resp = await  api.post('/m3/sp/add_upd',serviceProjectSaveOrUpdateParams)
  message.success(resp.message)
  await tableRef.value?.requestGetTableData()
  await closeModal()

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

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


<style  lang="scss">
.securityServiceContract{
   color: red;
}
</style>
