<template>

  <view class="example">
    <uni-forms ref="formRef" :modelValue="formData" :rules="rules" validateTrigger="submit" label-position="top">
      <uni-forms-item label="项目成员" required label-width="90px" name="account_id">
        <view class="custom-select-class" @click="showTreeSelectModal(allowedAccountList, 0, [formData.account_id])">
          <view class="custom-select-content">
            <text v-if="formData.account_id">{{ formData.account_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="role_id">
        <view class="custom-select-class" @click="showTreeSelectModal(roleList, 1, [formData.role_id])">
          <view class="custom-select-content">
            <text v-if="formData.role_id">{{ formData.role_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="intro">
        <uni-easyinput type="textarea" v-model="formData.memo" placeholder="备注信息" />
      </uni-forms-item>
    </uni-forms>
    <view style="margin-bottom: 10px;">
      <custom-button width="100%" type="filled" color="#007aff" @click="handlerAddProjectMember()">添加</custom-button>
    </view>
    <next-tree :ifSearch="true" :border="true" labelKey="name" ref="treeSelectRef" funcMode="radio"
      :treeData="treeSelectData" @confirm="confirmTreeSelect" @cancel="cancelTreeSelect"></next-tree>
  </view>

</template>

<script lang="ts" setup>
import { getMemberRoleList } 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 { addMember, getMemberList } from '@/api/project-center/member';
import { Members } from '@/types/member';

const treeDataType = ref<number>(0)
const accountList = ref<{ id: string, name: string }[]>([])
const roleList = ref<{ id: string, name: string }[]>([])
const treeSelectData = ref<DomainTree[]>([]) // 区域树
const formRef = ref()
const treeSelectRef = ref()
const { emitter } = useEmitt()
const memberList = ref<Members[]>([])

const rules = {
  account_id: {
    rules: [
      {
        required: true,
        errorMessage: '项目组成员不能为空',
      }
    ]
  },
  role_id: {
    rules: [
      {
        required: true,
        errorMessage: '成员角色不能为空',
      }
    ]
  }
}

const formData = ref<{
  prj_id?: string
  account_id?: string // 项目负责人账号id
  account_name?: string
  role_id?: string // 商务负责人id
  role_name?: string // 商务负责人id
  memo?: string
}>({})



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
}

const allowedAccountList = computed(() => {
  const accounts = accountList.value.filter(item => {
    if (memberList.value.findIndex(m => m.account_id === item.id) === -1) {
      return true
    }
    return false
  })
  return accounts
})


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

const getRoles = async () => {
  const { list } = await getMemberRoleList()
  roleList.value = list
}

// 获取项目组成员
const getMembers = async (prj_id: string) => {
  const { list } = await getMemberList({ prj_id })
  memberList.value = list
}





function confirmTreeSelect(list: any) {
  switch (treeDataType.value) {
    case 0:
      if (list.length > 0) {
        formData.value.account_id = list[0].id
        formData.value.account_name = list[0].name
      } else {
        formData.value.account_id = undefined
        formData.value.account_name = undefined
      }
      break;
    case 1:
      if (list.length > 0) {
        formData.value.role_id = list[0].id
        formData.value.role_name = list[0].name
      } else {
        formData.value.role_id = undefined
        formData.value.role_name = undefined
      }
      break;
    default:
      break;
  }
  treeSelectData.value = [];
}


const cancelTreeSelect = () => {
  treeSelectData.value = []
}

/**
 * 确认添加项目组成员
 */

const handlerAddProjectMember = async () => {
  const isValid = await formRef.value?.validate()
  if (!isValid) {
    return
  }
  const { prj_id, account_id, role_id, memo } = unref(formData)
  await addMember({
    prj_id: prj_id!,
    account_id: account_id!,
    role_id: role_id!,
    memo: memo
  })
  emitter.emit('get_project_detail', prj_id)
  uni.showModal({
    title: '添加成功',
    success: (res: { confirm: boolean }) => {
      const { confirm } = res;
      if (confirm) {
        return uni.navigateBack()
      }
    }
  })
}


const restForm = async () => {
  formData.value = {}
  formRef.value?.clearValidate()
}

onLoad((option) => {
  formData.value.prj_id = option?.id
  getMembers(option?.id!)
});


onMounted(() => {
  getAccountList()
  getRoles()
})

</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>