<template>

  <view class="example">
    <uni-forms ref="formRef" :modelValue="formData" :rules="rules" validateTrigger="submit" label-position="top">
      <uni-forms-item label="审核成员" required label-width="120px" name="account_id">
        <view class="custom-select-class" @click="showTreeSelectModal(allowedAccountList, [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="120px" name="due_day">
        <view style="margin-top:5px;">
          <uni-number-box v-model="formData.due_day" :min="3" />
        </view>
      </uni-forms-item>
    </uni-forms>
    <view style="margin-bottom: 10px;">
      <custom-button width="100%" type="filled" color="#007aff" @click="handlerAddChecker()">添加</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 { 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 { Checker } from '@/types/project';
import { getProjectCheckers, setProjectCheckers } from '@/api/project-center/info';

const accountList = ref<{ id: string, name: string }[]>([])
const checkers = ref<Checker[]>([])
const treeSelectData = ref<DomainTree[]>([]) // 区域树
const formRef = ref()
const treeSelectRef = ref()
const { emitter } = useEmitt()

const rules = {
  account_id: {
    rules: [
      {
        required: true,
        errorMessage: '审核成员不能为空',
      }
    ]
  },
  due_day: {
    rules: [
      {
        required: true,
        errorMessage: '超时时限不能为空',
      }
    ]
  }
}

const formData = ref<{
  prj_id?: string
  account_id?: string // 项目负责人账号id
  account_name?: string
  due_day: number
}>({
  due_day: 3
})



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, selectId?: any) => {
  treeSelectData.value = treeData;
  checkedTreeData(treeSelectData.value, selectId)
  unref(treeSelectRef).showTree = true
}

const allowedAccountList = computed(() => {
  const accounts = accountList.value.filter(item => {
    if (checkers.value.findIndex(m => m.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 getCheckers = async (id: string) => {
  const { checkers: list } = await getProjectCheckers({ id })
  checkers.value = list
}


function confirmTreeSelect(list: any) {
  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
  }
  treeSelectData.value = [];
}


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

/**
 * 确认添加审核组成员
 */
const handlerAddChecker = async () => {
  const isValid = await formRef.value?.validate()
  if (!isValid) {
    return
  }
  const { prj_id, account_id, due_day, account_name } = unref(formData)
  checkers.value.push({
    due_day: due_day!,
    id: account_id!,
    name: account_name!
  })
  await setProjectCheckers({
    id: prj_id!,
    checkers: checkers.value
  })
  emitter.emit('get_project_checkers')
  uni.showModal({
    title: '添加成功',
    success: (res: { confirm: boolean }) => {
      const { confirm } = res;
      if (confirm) {
        return uni.navigateBack()
      }
    }
  })
}


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


onMounted(() => {
  getAccountList()

})

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