<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">{{ allowedAccountList.find(item => item.id === formData.account_id)?.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="1" />
        </view>
      </uni-forms-item>
    </uni-forms>
    <view style="margin-bottom: 10px;">
      <custom-button width="100%" type="filled" color="#4cd964" @click="handlerModifyChecker()">修改</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, disabled?: boolean }[]>([])
const checkers = ref<Checker[]>([])
const treeSelectData = ref<DomainTree[]>([]) // 区域树
const formRef = ref()
const treeSelectRef = ref()
const { emitter } = useEmitt()
const selected_account_id = ref()


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: 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, 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.filter(c => c.id !== selected_account_id.value).findIndex(m => m.id === item.id) === -1) {

    } else {
      item.disabled = true
    }
    return true
  })
  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
  // formData.value.account_name = list.find(item=> item.id === formData.value.account_id)?.name
}


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 handlerModifyChecker = async () => {
  const isValid = await formRef.value?.validate()
  if (!isValid) {
    return
  }
  const { prj_id, account_id, due_day, account_name } = unref(formData)
  const index = checkers.value.findIndex(item => item.id === selected_account_id.value)
  checkers.value.splice(index, 1, {
    id: account_id!,
    due_day: due_day!,
    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
  formData.value.account_id = option?.account_id
  selected_account_id.value = option?.account_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>