<template>

  <view class="example">
    <uni-forms ref="planFormRef" :modelValue="planFormData" :rules="rules" validateTrigger="submit" label-position="top">
      <uni-forms-item :label="'任务名称'" required label-width="105px" name="name">
        <uni-easyinput v-model="planFormData.name" placeholder="请输入任务名称" :disabled="!editable(ui_status.name)" />
      </uni-forms-item>
      <uni-forms-item label="主负责人" required label-width="105px" name="handler_id">
        <view class="custom-select-class" @click="showTreeSelectModal([planFormData.handler_id])" :style="{
          background: !editable(ui_status.handler_name) ? '#f7f6f6' : undefined,
          cursor: !editable(ui_status.handler_name) ? 'not-allowed' : undefined,
          color: !editable(ui_status.handler_name) ? '#d5d5d5' : undefined
        }">
          <view class="custom-select-content">
            <text v-if="planFormData.handler_id">{{ planFormData.handler_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="105px" name="progress">
        <custom-progress v-if="!editable(ui_status.progress)" :value="planFormData.progress" style="min-width: 250px"
          :stroke-width="16"></custom-progress>
        <slider v-else :value="planFormData.progress" step="1" show-value :block-size="20" @change="updateProgress"
          style="margin: 10px 0" :disabled="!editable(ui_status.progress)" />
      </uni-forms-item> -->
      <uni-forms-item label="计划开始时间" required label-width="105px" name="begin_at">
        <uni-datetime-picker type="date" v-model="planFormData.begin_at" :disabled="!editable(ui_status.begin_at)" />
      </uni-forms-item>
      <uni-forms-item label="预计结束时间" required label-width="105px" name="end_at">
        <uni-datetime-picker type="date" v-model="planFormData.end_at" :disabled="!editable(ui_status.end_at)" />
      </uni-forms-item>
    </uni-forms>
    <view style="margin-bottom: 10px;display: flex;">
      <custom-button width="100%" type="filled" color="#4cd964" @click="handlerModifyPlan()"
        style="flex:1">修改</custom-button>
    </view>
    <next-tree :ifSearch="true" :border="true" labelKey="name" ref="treeSelectRef" :checkStrictly="true"
      :funcMode="'radio'" :treeData="accountList" @confirm="confirmTreeSelect" @cancel="cancelTreeSelect"></next-tree>
  </view>

</template>

<script lang="ts" setup>
import { getStaffList } from '@/api/biz/staff';
import { getPlanTaskDetail, modifyPlanTask } from '@/api/project-center/plan-task';
import nextTree from '@/components/next-tree/next-tree.vue'
import { OperateTypeItem } from '@/enums/api';
import { useEmitt } from '@/logics/mitt/useEmitt';
import { ModifyTaskReqParams, UiStatus } from '@/types/plan-task';


const accountList = ref<{ id: string, name: string }[]>([])
const planFormRef = ref()
const treeSelectRef = ref()
const { emitter } = useEmitt()

const ui_status = reactive<Omit<UiStatus, 'alter'>>({
  name: OperateTypeItem.RW,
  // progress: OperateTypeItem.RW,
  status: OperateTypeItem.RW,
  handler_name: OperateTypeItem.RW,
  begin_at: OperateTypeItem.RW,
  end_at: OperateTypeItem.RW,
})

/**
 * 是否是编辑
 * @param type
 */
const editable = (type?: string) => {
  return type === OperateTypeItem.RW || type === OperateTypeItem.W
}

const rules = {
  // 对name字段进行必填验证
  name: {
    // name 字段的校验规则
    rules: [
      // 校验 name 不能为空
      {
        required: true,
        errorMessage: '名称不能为空',
      }
    ]
  },
  handler_id: {
    rules: [
      {
        required: true,
        errorMessage: '负责人不能为空',
      }
    ]
  },
  end_at: {
    rules: [
      {
        required: true,
        errorMessage: '预计结束时间不能为空',
      }
    ]
  },
  begin_at: {
    rules: [
      {
        required: true,
        errorMessage: '任务开始不能为空',
      }
    ]
  },
}
const planFormData = ref<{
  id?: string
  name?: string
  handler_id?: string // 
  handler_name?: string
  begin_at?: string,
  // progress?: number
  end_at?: string
  draft?: boolean
}>({})



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)
    }
  })
}

// 显示modal
const showTreeSelectModal = async (selectId?: any) => {
  if (!editable(ui_status.handler_name)) {
    return
  }
  checkedTreeData(accountList.value, selectId)
  unref(treeSelectRef).showTree = true
}



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

const getDetail = async (id: string, draft: boolean) => {
  const detail = await getPlanTaskDetail({ task_id: id, draft })
  planFormData.value.id = detail.task_id,
    planFormData.value.handler_id = detail.handler_id
  planFormData.value.name = detail.name;
  planFormData.value.handler_name = detail.handler_name;
  // planFormData.value.progress = detail.progress
  planFormData.value.begin_at = detail.begin_at;
  planFormData.value.end_at = detail.end_at
}


function confirmTreeSelect(list: { id: string, name: string }[]) {
  if (list.length > 0) {
    planFormData.value.handler_id = list[0].id
    planFormData.value.handler_name = list[0].name
  }
}


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



const handlerModifyPlan = async () => {
  const isValid = await planFormRef.value?.validate()
  if (!isValid) {
    return
  }
  const { id, name, handler_id, begin_at, end_at, draft } = unref(planFormData)
  const params: ModifyTaskReqParams = {
    task_id: id!,
    draft: draft!,
    handler_id: !editable(ui_status.handler_name) ? undefined : handler_id,
    name: !editable(ui_status.name) ? undefined : name,
    // progress: !editable(ui_status.progress)? undefined: progress,
    begin_at: !editable(ui_status.begin_at) ? undefined : begin_at,
    end_at: !editable(ui_status.end_at) ? undefined : end_at
  }
  await modifyPlanTask(params)

  uni.showModal({
    title: '修改成功',
    content: `是否返回计划列表`,
    success: (res: { confirm: boolean }) => {
      const { confirm } = res;
      if (confirm) {
        setTimeout(() => {
          emitter.emit('get_task_list')
          uni.navigateBack()
        }, 1500)
        return
      }
    }
  })
  // const {}
}

onLoad((option) => {
  // planFormData.value.id = option.task_id
  planFormData.value.draft = JSON.parse(option?.draft as string)
  getAccountList()
  getDetail(option?.task_id as string, JSON.parse(option?.draft as string))
  const rw = option?.rw?.split(',') as string[]
  ui_status.name = rw[0];
  ui_status.handler_name = rw[1]
  ui_status.begin_at = rw[2];
  ui_status.end_at = rw[3];

});



onMounted(() => {

})

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

}
</script>
<style scoped>
.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;

}

:deep(.ayi-progress) {
  height: 100%;
}

:deep(.ayi-progress__text) {
  text-align: right !important;
  width: 50rpx !important;
}
</style>