<template>

  <view class="example">
    <!-- 展示不同的排列方式 -->
    <uni-forms ref="projectFormRef" :modelValue="projectFormData" :rules="rules" validateTrigger="submit"
      label-position="top">
      <uni-forms-item label="项目名称" required label-width="90px" name="name">
        <uni-easyinput v-model="projectFormData.name" placeholder="请输入项目名称" />
      </uni-forms-item>
      <uni-forms-item label="所在地区" required label-width="90px" name="region_id">
        <view class="custom-select-class" @click="showTreeSelectModal(regionTreeData, 0, [projectFormData.region_id])">
          <view class="custom-select-content">
            <text v-if="projectFormData.region_id">{{ projectFormData.region_name }}</text>
            <text v-else style="color:#909399;font-size: 12px;">请选择项目所在地区</text>
          </view>
          <uni-icons :size="14" color="#909399" type="down" style=" padding: 0 5px;"></uni-icons>
        </view>
      </uni-forms-item>
      <uni-forms-item label="项目类型" required label-width="90px" name="type_id">
        <view class="custom-select-class" @click="showTreeSelectModal(typeTreeData, 1, [projectFormData.type_id])">
          <view class="custom-select-content">
            <text v-if="projectFormData.type_id">{{ projectFormData.type_name }}</text>
            <text v-else style="color:#909399;font-size: 12px;">请选择项目类型</text>
          </view>
          <uni-icons :size="14" color="#909399" type="down" style=" padding: 0 5px;"></uni-icons>
        </view>
      </uni-forms-item>
      <uni-forms-item label="项目客户" label-width="90px" name="level_id">
        <view class="custom-select-class" @click="showTreeSelectModal(customerList, 2, [projectFormData.customer_id])">
          <view class="custom-select-content">
            <text v-if="projectFormData.customer_id">{{ projectFormData.customer_name }}</text>
            <text v-else style="color:#909399;font-size: 12px;">请选择客户信息</text>
          </view>
          <uni-icons :size="14" color="#909399" type="down" style=" padding: 0 5px;"></uni-icons>
        </view>
      </uni-forms-item>
      <uni-forms-item label="合同信息" label-width="90px" name="contract_id">
        <view class="custom-select-class" @click="showTreeSelectModal(contractList, 3, [projectFormData.contract_id])">
          <view class="custom-select-content">
            <text v-if="projectFormData.contract_id">{{ projectFormData.contract_name }}</text>
            <text v-else style="color:#909399;font-size: 12px;">请选择合同信息</text>
          </view>
          <uni-icons :size="14" color="#909399" type="down" style=" padding: 0 5px;"></uni-icons>
        </view>
      </uni-forms-item>
      <uni-forms-item label="预计交付" required label-width="90px" name="deliver_at">
        <uni-datetime-picker type="date" v-model="projectFormData.deliver_at" />
      </uni-forms-item>
      <!-- <uni-forms-item label="项目负责人" required label-width="90px" name="leader_id">
        <view class="custom-select-class" @click="showTreeSelectModal(accountList, 4, [projectFormData.leader_id])">
          <view class="custom-select-content">
            <text v-if="projectFormData.leader_id">{{ projectFormData.leader_name }}</text>
            <text v-else style="color:#909399;font-size: 12px;">请选择项目负责人</text>
          </view>
          <uni-icons :size="14" color="#909399" type="down" style=" padding: 0 5px;"></uni-icons>
        </view>
      </uni-forms-item> -->
      <!-- <uni-forms-item label="商务负责人" required label-width="90px" name="bizman_id">
        <view class="custom-select-class" @click="showTreeSelectModal(accountList, 5, [projectFormData.bizman_id])">
          <view class="custom-select-content">
            <text v-if="projectFormData.bizman_id">{{ projectFormData.bizman_name }}</text>
            <text v-else style="color:#909399;font-size: 12px;">请选择商务负责人</text>
          </view>
          <uni-icons :size="14" color="#909399" type="down" style=" padding: 0 5px;"></uni-icons>
        </view>
      </uni-forms-item> -->
      <uni-forms-item label="审核组成员" required label-width="90px" name="bizman_id">
        <view class="custom-select-class"
          @click="showTreeSelectModal(accountList, 6, projectFormData.checker_ids || [])">
          <view class="custom-select-content">
            <view v-if="projectFormData.checker_ids && projectFormData.checker_ids.length > 0" class="tag-container">
              <uni-tag :text="item" :inverted="true"
                :custom-style='"font-weight:bolder;border: 1px solid transparent;background:#e8f3ff;color:rgb(22, 93, 255);"'
                class="tag-container__item" v-for="item in projectFormData.checker_names?.slice(0, 2)" :key="item">
              </uni-tag>
              <uni-tag :inverted="true" type="primary" v-if="projectFormData.checker_ids.length > 2"
                :custom-style='"font-weight:bolder;border: 1px solid transparent;background:#e8f3ff;color:rgb(22, 93, 255);"'
                :text="`+${projectFormData.checker_ids.length - 2}...`" />
            </view>
            <text v-else style="color:#909399;font-size: 12px;">请选择审核组成员</text>
          </view>
          <uni-icons :size="14" color="#909399" type="down" style=" padding: 0 5px;"></uni-icons>
        </view>
      </uni-forms-item>
      <uni-forms-item label="项目简介" label-width="90px" name="intro">
        <uni-easyinput type="textarea" v-model="projectFormData.intro" placeholder="请输入项目备注信息" />
      </uni-forms-item>
    </uni-forms>
    <view style="margin-bottom: 10px;display: flex;">
      <custom-button width="100%" type="filled" color="#dd524d" @click="restForm()"
        style="margin-right: 5px;flex:1">重置</custom-button>
      <custom-button width="100%" type="filled" color="#007aff" style="flex:1;"
        @click="handlerAddProject()">提交</custom-button>
    </view>
    <next-tree :ifSearch="true" :showAuxiliaryLine="[0, 1].includes(treeDataType)" :border="true" labelKey="name"
      ref="treeSelectRef" :checkStrictly="true" :selectParent="![1].includes(treeDataType)"
      :funcMode="[6].includes(treeDataType) ? 'checkbox' : 'radio'" :treeData="treeSelectData"
      @confirm="confirmTreeSelect" @cancel="cancelTreeSelect"></next-tree>
  </view>

</template>

<script lang="ts" setup>
import { getPrjTypeList } from '@/api/base/base';
import { getStaffList } from '@/api/biz/staff';
import nextTree from '@/components/next-tree/next-tree.vue'
import { DomainTree } from '@/types/domain';
import { useEmitt } from '@/logics/mitt/useEmitt';
import { addProject } from '@/api/project-center/info';
import { AddProjectReqParams } from '@/types/project';
import { getCustomerList } from '@/api/biz/customer';
import { getContractList } from '@/api/project-center/contract';
import { getRegionTree } from '@/api/base/region';
import { useUserStore } from '@/stores';
import {
  Customer as CustomerApi,
  Project as ProjectApi
} from '@/enums/api'

const treeDataType = ref<number>(0)
const accountList = ref<{ id: string, name: string }[]>([])
const customerList = ref<{ id: string, name: string }[]>([])
const contractList = ref<{ id: string, name: string }[]>([])
const treeSelectData = ref<DomainTree[]>([]) // 区域树
const regionTreeData = ref<DomainTree[]>([]) // 区域树
const typeTreeData = ref<DomainTree[]>([])
const projectFormRef = ref()
const treeSelectRef = ref()
const { emitter } = useEmitt()
const userStore = useUserStore()
const permissionsList = userStore.getPermissionsList
const rules = {
  // 对name字段进行必填验证
  name: {
    // name 字段的校验规则
    rules: [
      // 校验 name 不能为空
      {
        required: true,
        errorMessage: '名称不能为空',
      }
    ]
  },
  region_id: {
    rules: [
      {
        required: true,
        errorMessage: '所属区域不能为空',
      }
    ]
  },

  type_id: {
    rules: [
      {
        required: true,
        errorMessage: '项目类型不能为空',
      }
    ]
  },
  deliver_at: {
    rules: [
      {
        required: true,
        errorMessage: '立项时间不能为空',
      }
    ]
  },
  checker_ids: {
    rules: [
      {
        required: true,
        errorMessage: '审核组成员不能为空',
      }
    ]
  },
}
const projectFormData = ref<{
  name?: string
  customer_id?: string // 项目id
  customer_name?: string // 项目id
  region_id?: number // 所在地区id
  type_id?: number // 项目子类型id
  type_name?: string
  template_id?: string // 项目模板，通过模板可以自动生成项目任务计划
  deliver_at?: string // 预计交付时间（YYYY-MM-DD）
  contract_id?: string // 合同编号
  contract_name?: string
  // leader_id?: string // 项目负责人账号id
  // leader_name?: string
  // bizman_id?: string // 商务负责人id
  // bizman_name?: string // 商务负责人id
  region_name?: string
  intro?: string // 项目简介
  checker_ids?: string[]
  checker_names?: string[]
}>({})


// 是否授权客户信息
const isAuthCustomer = computed(() => {
  return (
    permissionsList?.findIndex(
      item => `api/${item}` === CustomerApi.BIZ_CUSTOMER_LIST
    ) !== -1
  )
})

// 是否授权客户信息
const isAuthContract = computed(() => {
  return (
    permissionsList?.findIndex(
      item => `api/${item}` === ProjectApi.PROJECT_CONTRACT_LIST
    ) !== -1
  )
})

function checkedTreeData(treeData: any, selectIds?: any) {
  treeData.map((item: any) => {
    if (selectIds.indexOf(item.id) !== -1) {
      item.checked = true
    } else {
      item.checked = false
    }
    if (item.children && item.children.length) {
      checkedTreeData(item.children, selectIds)
    }
  })
}

const showTreeSelectModal = async (treeData: any, type: number, selectId?: any) => {
  treeDataType.value = type;
  treeSelectData.value = treeData;
  checkedTreeData(treeSelectData.value, selectId)
  unref(treeSelectRef).showTree = true
}

/**
 * 递归获取ng-tree需要的结构体
 * @param domains 接口返回的树状数组
 */
const getNodesTree = (domains: DomainTree): DomainTree => {
  domains.key = domains.id.toString()
  if (domains.children && domains.children.length > 0) {
    domains.children.map(res => getNodesTree(res))
  }
  return domains
}

/**
 * 获取区域树
 */
const getTree = async () => {
  const { tree } = await getRegionTree()
  regionTreeData.value = tree
}

/**
* 获取用户列表
*/
const getAccountList = async () => {
  try {
    const { list } = await getStaffList({ page_no: 1, page_size: 9999 })
    accountList.value = list
  } catch (e) {
    console.error(e)
  }
}

const getProjectType = async () => {
  const { tree } = await getPrjTypeList()
  typeTreeData.value = tree.map(domains => {
    return getNodesTree(domains)
  })
}


// 获取客户列表
const getCustomers = async () => {
  if (isAuthCustomer.value) {
    try {
      const params = {
        page_no: 1,
        page_size: 9999,
      }
      const { list } = await getCustomerList(params)
      customerList.value = list
    } catch (e) {
      console.error(e)
    }
  }

}

const getContracts = async (name?: string) => {
  if (isAuthContract.value) {
  try {
    const { list } = await getContractList({ page_no: 1, page_size: 9999, binded: false })
    contractList.value = list
  } catch (e) {
    console.error(e)
  }
}
}



function confirmTreeSelect(list: any) {
  switch (treeDataType.value) {
    case 0:
      if (list.length > 0) {
        projectFormData.value.region_id = list[0].id
        projectFormData.value.region_name = list[0].name
      } else {
        projectFormData.value.region_id = undefined
        projectFormData.value.region_name = undefined
      }
      break;
    case 1:
      if (list.length > 0) {
        projectFormData.value.type_id = list[0].id
        projectFormData.value.type_name = list[0].name
      } else {
        projectFormData.value.type_id = undefined
        projectFormData.value.type_name = undefined
      }
      break;
    case 2:
      if (list.length > 0) {
        projectFormData.value.customer_id = list[0].id
        projectFormData.value.customer_name = list[0].name
      } else {
        projectFormData.value.customer_id = undefined
        projectFormData.value.customer_name = undefined
      }
      break;
    case 3:
      if (list.length > 0) {
        projectFormData.value.contract_id = list[0].id
        projectFormData.value.contract_name = list[0].name
      } else {
        projectFormData.value.contract_id = undefined
        projectFormData.value.contract_name = undefined
      }
      break;
    // case 4:
    //   if (list.length > 0) {
    //     projectFormData.value.leader_id = list[0].id
    //     projectFormData.value.leader_name = list[0].name
    //   } else {
    //     projectFormData.value.leader_id = undefined
    //     projectFormData.value.leader_name = undefined
    //   }
    //   break;
    // case 5:
    //   if (list.length > 0) {
    //     projectFormData.value.bizman_id = list[0].id
    //     projectFormData.value.bizman_name = list[0].name
    //   } else {
    //     projectFormData.value.bizman_id = undefined
    //     projectFormData.value.bizman_name = undefined
    //   }
    //   break;
    case 6:
      if (list.length > 0) {
        projectFormData.value.checker_ids = []
        projectFormData.value.checker_names = []
        list.map((item: any) => {
          projectFormData.value.checker_ids?.push(item.id)
          projectFormData.value.checker_names?.push(item.name)
          return item
        })
      } else {
        projectFormData.value.checker_ids = undefined
        projectFormData.value.checker_names = undefined
      }
      break;
    default:
      break;
  }
  treeSelectData.value = [];
}


const cancelTreeSelect = () => {
  treeSelectData.value = []
  // checkedTreeData(unref(tr), []) 
}




const handlerAddProject = async () => {
  const isValid = await projectFormRef.value?.validate()
  console.log(isValid)
  if (!isValid) {
    return
  }
  const { name, region_id,
    customer_id, // 项目id
    type_id, // 项目子类型id
    deliver_at, // 预计交付时间（YYYY-MM-DD）
    contract_id, // 合同编号
    // leader_id, // 项目负责人账号id
    // bizman_id, // 商务负责人id
    intro, // 项目简介
    checker_ids
  } = unref(projectFormData)
  const params: AddProjectReqParams = {
    name: name!,
    region_id: region_id!,
    customer_id,
    type_id: type_id!,
    deliver_at,
    contract_id,
    // bizman_id: bizman_id!,
    // leader_id: leader_id!,
    intro,
    checker_ids: checker_ids!
  }
  await addProject(params)
  emitter.emit('get_project_list')
  uni.showModal({
    title: '添加成功',
    content: `是否返回项目管理页面`,
    success: (res: { confirm: boolean }) => {
      const { confirm } = res;
      if (confirm) {
        return uni.navigateBack()
      }
    }
  })
  // const {}
}


const restForm = async () => {
  projectFormData.value = {}
  projectFormRef.value?.clearValidate()
  console.log(projectFormRef.value)

}


onMounted(() => {
  getAccountList()
  getTree()
  getContracts()
  getCustomers()
  getProjectType()
})

</script>
<script lang="ts">
export default {
  options: {
    styleIsolation: 'apply-shared', //解除样式隔离
  }

}
</script>
<style scoped lang="scss">
.example {
  padding: 15px;
  background-color: #fff;
}

:deep(.is-disabled) {
  color: #333;

}

.custom-select-class {
  border-color: #e5e5e5;
  background-color: transparent;
  display: flex;
  box-sizing: border-box;
  flex-direction: row;
  align-items: center;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.custom-select-content {
  width: auto;
  position: relative;
  overflow: hidden;
  flex: 1;
  line-height: 1;
  font-size: 14px;
  line-height: 35px;
  padding-left: 10px;
  height: 35px;

}

.tag-container {
  &__item {
    padding: 0 6px 0 0;
  }
}
</style>