<template>
  <view class="add">
    <view class="form">
      <uv-form
        labelPosition="left"
        :model="form"
        :rules="rules"
        ref="formRef"
        labelWidth="120"
        :labelStyle="labelStyle"
      >
        <uv-form-item label="执行包名称" prop="scorePackageName" borderBottom required>
          <uv-input
            v-model="form.scorePackageName"
            border="none"
            placeholder="请输入"
            :readonly="formDisabled"
          />
        </uv-form-item>
        <uv-form-item
          label="承接对象类型"
          prop="typeidLabel"
          borderBottom
          @click="showSelect('typeidLabel')"
          required
        >
          <uv-input v-model="form.typeidLabel" border="none" placeholder="请选择" readonly />
          <template v-slot:right>
            <uv-icon name="arrow-right"></uv-icon>
          </template>
        </uv-form-item>
        <uv-form-item
          v-if="userListShow"
          label="承接对象"
          prop="userListLabel"
          borderBottom
          @click="showSelect('userListLabel')"
          required
        >
          <uv-input v-model="form.userListLabel" border="none" placeholder="请选择" readonly />
          <template v-slot:right>
            <uv-icon name="arrow-right"></uv-icon>
          </template>
        </uv-form-item>
        <uv-form-item
          label="关联服务企业"
          prop="relatedServiceLabel"
          borderBottom
          @click="showSelect('relatedServiceLabel')"
          required
        >
          <uv-input
            v-model="form.relatedServiceLabel"
            border="none"
            placeholder="请选择"
            readonly
          />
          <template v-slot:right>
            <uv-icon name="arrow-right"></uv-icon>
          </template>
        </uv-form-item>
        <uv-form-item
          label="关联执行包名称"
          prop="relationScoreIdLable"
          borderBottom
          @click="showSelect('relationScoreIdLable')"
          required
        >
          <uv-input
            v-model="form.relationScoreIdLable"
            border="none"
            placeholder="请选择"
            readonly
          />
          <template v-slot:right>
            <uv-icon name="arrow-right"></uv-icon>
          </template>
        </uv-form-item>
        <uv-form-item label="推广产品" prop="drugtableLabel" borderBottom>
          <uv-input v-model="form.drugtableLabel" border="none" placeholder="请选择" readonly />
        </uv-form-item>
        <uv-form-item label="可分配积分值" prop="kfpjf" borderBottom>
          <uv-input v-model="form.kfpjf" type="number" readonly border="none" />
        </uv-form-item>
        <uv-form-item label="服务总值" prop="score" borderBottom required>
          <uv-input v-model="form.score" type="number" readonly border="none" />
        </uv-form-item>
        <uv-form-item
          label="接单对象范围"
          prop="packageUserScopeLable"
          borderBottom
          @click="showSelect('packageUserScopeLable')"
          required
        >
          <uv-input
            v-model="form.packageUserScopeLable"
            border="none"
            placeholder="请选择"
            readonly
          />
          <template v-slot:right>
            <uv-icon name="arrow-right"></uv-icon>
          </template>
        </uv-form-item>
        <uv-form-item label="生效日期" prop="startTime" borderBottom required>
          <uv-input
            prefixIcon="calendar"
            prefixIconStyle="font-size: 22px;color: #909399"
            v-model="form.startTime"
            border="none"
            placeholder="请选择"
            readonly
          />
        </uv-form-item>
        <uv-form-item label="截止日期" prop="endTimeValue" borderBottom required>
          <uv-input
            prefixIcon="calendar"
            prefixIconStyle="font-size: 22px;color: #909399"
            v-model="form.endTimeValue"
            border="none"
            placeholder="请选择"
            readonly
          />
        </uv-form-item>
        <uv-form-item label="执行包编号" prop="packageSn" borderBottom>
          <uv-input v-model="form.packageSn" type="number" readonly border="none" />
        </uv-form-item>
        <uv-form-item label="有效任务类型如下：" labelWidth="140" labelPosition="top" placeholder>
          <!-- <taskTree ref="taskTreeRef" /> -->
          <TableData
            ref="tableRef"
            @updateScope="
              (val) => {
                form.score = val
              }
            "
          />
        </uv-form-item>
        <uv-form-item label="描述" prop="description" borderBottom labelWidth="40">
          <uv-textarea
            v-model="form.description"
            placeholder="请输入内容"
            height="48"
          ></uv-textarea>
        </uv-form-item>
      </uv-form>
    </view>
    <view class="btn">
      <view class="cancel" @click="cancelFn">取消</view>
      <view class="confirm" @click="confirmFn(0)">确定</view>
      <!-- <view class="confirm" @click="confirmFn(1)">确定并继续</view> -->
    </view>
    <!-- 选择承接对象类型 -->
    <uv-picker
      ref="typeidPickerRef"
      :columns="[personalList]"
      keyName="label"
      @confirm="(e: any) => pickerConfim(e, 'typeidLabel')"
    />
    <!-- 选择承接对象类型 -->
    <uv-picker
      ref="userListPickerRef"
      :columns="[objectScopeList5]"
      keyName="label"
      @confirm="(e: any) => pickerConfim(e, 'userListLabel')"
    />
    <!-- 选择关联服务企业 -->
    <uv-picker
      ref="relatedServicePickerRef"
      :columns="[allParentDeptList]"
      keyName="name"
      @confirm="(e: any) => pickerConfim(e, 'relatedServiceLabel')"
    />
    <!-- 选择关联执行包 -->
    <uv-picker
      ref="relationScoreIdPickerRef"
      :columns="[relationScoreList]"
      keyName="scorePackageName"
      @confirm="(e: any) => pickerConfim(e, 'relationScoreIdLable')"
    />
  </view>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { reactive, ref, toRaw } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import {
  getTypeidPersonalApi,
  getObjectScopeListApi,
  getWmscorepackageSnApi,
  getPackageScopeListApi,
  getListAncestor,
  getRelationScoreListApi,
  addWmScorePackageApi
} from '@/service/modules/assignPoints'

import TableData from './components/TableData.vue'
import { pFlist } from './components/treeList'

const currentType = ref()
const startDate = dayjs().format('YYYY-MM-DD')
onLoad((e: any) => {
  currentType.value = e?.type

  getDict()
})

const personalList = ref<any[]>([])
// 全职人员
const objectScopeList5 = ref<any[]>([])
// 分类
const packageScopeList = ref<any[]>([])
// 关联服务企业
const allParentDeptList = ref<any[]>([])
const getDict = () => {
  getTypeidPersonalApi().then((res: any) => {
    const arr: any[] = []
    res.data.forEach((item: any) => {
      const addnew = {
        value: item.value,
        label: item.label
      }
      arr.push(addnew)
    })
    personalList.value = arr.filter((item) => item.value === '3')
  })
  getObjectScopeListApi('5').then((res: any) => {
    objectScopeList5.value = res.data?.map((item: any) => {
      return {
        value: item.id,
        label: item.realname + ' ' + item.username
      }
    })
  })
  getPackageScopeListApi().then((res: any) => {
    packageScopeList.value = res.data
    if (currentType.value === '1') {
      form.packageUserScope = res.data[0].value
      form.packageUserScopeLable = res.data[0].label
    }
  })
  // 获取执行包编号
  if (currentType.value === '1') {
    getWmscorepackageSnApi().then((res: any) => (form.packageSn = res.data))
  }
  // 获取关联服务企业
  getListAncestor().then((res: any) => (allParentDeptList.value = res.data))
}

const formDisabled = ref(false)
const typeidPickerRef = ref()
const userListPickerRef = ref()
const relatedServicePickerRef = ref()
const relationScoreIdPickerRef = ref()

const showSelect = (type: string) => {
  if (formDisabled.value) return
  switch (type) {
    case 'typeidLabel':
      typeidPickerRef.value.open()
      break
    case 'userListLabel':
      if (form.typeid !== '3') return
      userListPickerRef.value.open()
      break
    case 'relatedServiceLabel':
      relatedServicePickerRef.value.open()
      break
    case 'relationScoreIdLable':
      if (!relationScoreList.value.length) return
      relationScoreIdPickerRef.value.open()
      break

    default:
      break
  }
}
// 控制是否可以选择接单对象范围
const packageUserScopeDisable = ref(false)
// 控制承接对象显示隐藏
const userListShow = ref(true)
const pickerConfim = (e: any, type: string) => {
  if (type === 'typeidLabel') {
    const value = e.value[0]
    form.typeid = value.value
    form.typeidLabel = value.label
    // 选择全职
    if (value?.value === '3') {
      packageUserScopeDisable.value = true
      form.packageUserScope = packageScopeList.value[0].value
      form.packageUserScopeLable = packageScopeList.value[0].label
      userListShow.value = true
    } else {
      userListShow.value = false
      form.userListLabel = ''
      form.userList = []
    }
  }
  if (type === 'userListLabel') {
    const value = e.value[0]
    form.userList = [value.value]
    form.userListLabel = value.label
  }
  if (type === 'relatedServiceLabel') {
    const value = e.value[0]
    form.relatedService = value.deptId + ''
    form.relatedServiceLabel = value.name
    form.relationScoreId = ''
    form.relationScoreIdLable = ''
    getRelationScoreListFn(value.deptId)
  }
  if (type === 'relationScoreIdLable') {
    const value = e.value[0]
    form.relationScoreId = value.id
    form.relationScoreIdLable = value.scorePackageName
    if (value.id === '-1') {
      form.kfpjf = ''
    } else {
      form.drugtable = value?.drugtable
      form.drugtableLabel = value?.drugtableName[0] || '测试qaq'
      initRelationScoreIdFn(value.id)
    }
  }
}

const tableRef = ref()

const relationScoreList = ref<any[]>([])
const getRelationScoreListFn = async (id: number) => {
  const obj = { relatedService: id }
  const res = await getRelationScoreListApi(obj)
  relationScoreList.value = res.data
}
const initRelationScoreIdFn = async (id: number) => {
  const obj = { id: id }
  const res = await getRelationScoreListApi(obj)
  if (res.code === 0) {
    form.kfpjf = res.data[0].kfpjf
    const pkgTaskTypeQtyList = res.data[0].pkgTaskTypeQtyList
    tableRef.value.setData(pkgTaskTypeQtyList, res.data[0].kfpjf)
    form.startTime = res.data[0]?.startTime
    form.endTimeValue = res.data[0]?.endTime
    form.drugtable = res.data[0]?.drugtable
    form.drugtableLabel = res.data[0]?.drugtableName[0] || '测试qaq'
  }
}
const cancelFn = () => {
  uni.navigateBack()
}

const confirmFn = (type: number) => {
  const tableData = tableRef.value.getData()

  let pkgTaskTypeQtyList = tableData.map((item: any) => {
    return {
      taskTypeName: item.taskTypeName,
      price: item.score,
      taskTypeId: item.taskTypeId,
      qty: item.qty ? Number(item.qty) : 0
    }
  })
  let treeArr = tableData.map((item: any) => {
    return {
      taskTypeName: item.taskTypeName,
      taskTypeId: item.orgTaskTypeId
    }
  })
  let flag = pkgTaskTypeQtyList.every((item: any) => item.qty == 0)
  if (flag) {
    return uni.showToast({
      title: '请选择具体任务',
      icon: 'none',
      duration: 800
    })
  }

  let arr = [...pFlist]
  tableData.forEach((item: any) => {
    const curr = arr.find((iten) => iten.taskTypeId === item.parent_id)
    if (curr) {
      curr.children.push({
        taskTypeId: item.orgTaskTypeId,
        taskTypeName: item.taskTypeName
      })
    }
  })
  let taskTypeList = []
  taskTypeList = arr.concat(treeArr).filter((item) => {
    if (!item.children || item.children.length > 0) {
      return item
    }
  })

  // data.forEach((item: any) => {
  //   taskTypeList = taskTypeList.concat(...item.children)
  // })
  formRef.value
    .validate()
    .then(async () => {
      if (form.typeid == '3') {
        if (!form.userListLabel) {
          return uni.showToast({
            title: '接单对象不能为空',
            icon: 'none',
            duration: 800
          })
        }
      }
      if (Number(form.score) > Number(form.kfpjf) && form.relationScoreId != '-1') {
        return uni.showToast({
          title: '可分配积分不足',
          icon: 'none'
        })
      }
      if (Number(form.score) === 0) {
        return uni.showToast({
          title: '服务总值必须大于0',
          icon: 'none'
        })
      }
      if (!taskTypeList?.length) {
        return uni.showToast({
          title: '有效服务类型不能为空',
          icon: 'none'
        })
      }
      form.taskTypeList = taskTypeList

      submitInfo(type, pkgTaskTypeQtyList)
    })
    .catch((err: any) => {
      console.log('err', err)
    })
}
const submitInfo = async (type: number, pkgTaskTypeQtyList: any) => {
  const obj: any = toRaw(form)
  obj.packageType1 = '1'
  obj.packageType2 = '1'
  obj.userNum = '1'
  obj.pkgTaskTypeQtyList = pkgTaskTypeQtyList
  const res = await addWmScorePackageApi(obj)
  if (res.code === 0) {
    uni.showToast({
      title: '添加成功',
      icon: 'none'
    })
    if (type === 0) {
      setTimeout(() => {
        uni.navigateBack()
      }, 1000)
    } else {
      form.kfpjf = (form.kfpjf as number) - (form.score as number)
      form.scorePackageName = ''
      getWmscorepackageSnApi().then((res: any) => (form.packageSn = res.data))
    }
  } else {
    uni.showToast({
      title: res?.msg,
      icon: 'none'
    })
  }
}
const labelStyle = {
  fontWeight: 400,
  fontSize: '30rpx',
  color: '#000'
}
const formRef = ref()
const form = reactive({
  scorePackageName: '',
  typeid: '',
  typeidLabel: '',
  userList: [] as any[],
  userListLabel: '',
  relatedService: '',
  relatedServiceLabel: '',
  relationScoreId: '',
  relationScoreIdLable: '',
  drugtable: [] as any[],
  drugtableLabel: '',
  kfpjf: '' as string | number,
  score: '' as string | number,
  packageUserScope: '',
  packageUserScopeLable: '',
  startTime: '',
  endTimeValue: '',
  packageSn: '',
  description: '',
  taskTypeList: [] as any[]
})
const rules = reactive({
  scorePackageName: {
    type: 'string',
    required: true,
    message: '请输入执行包名称',
    trigger: ['blur', 'change']
  },
  typeidLabel: {
    type: 'string',
    required: true,
    message: '请选择执行包名称',
    trigger: ['blur', 'change']
  },
  relatedServiceLabel: {
    type: 'string',
    required: true,
    message: '请选择关联服务企业',
    trigger: ['blur', 'change']
  },
  relationScoreIdLable: {
    type: 'string',
    required: true,
    message: '请选择关联执行包',
    trigger: ['blur', 'change']
  },
  packageUserScopeLable: {
    type: 'string',
    required: true,
    message: '请选择接单对象范围',
    trigger: ['blur', 'change']
  },
  endTimeValue: {
    type: 'string',
    required: true,
    message: '请选择接单对象范围',
    trigger: ['blur', 'change']
  }
})
</script>

<style lang="scss" scoped>
.add {
  background: #f2f2f2;
  min-height: 100vh;
  box-sizing: border-box;
  padding: 24rpx;
  .form {
    background: #fff;
    padding: 30rpx;
    border-radius: 12rpx;
  }
}
:deep(.uv-form-item__body__left) {
  padding-left: 18rpx;
}

.btn {
  margin-top: 20rpx;
  box-sizing: border-box;
  width: 700rpx;
  height: 160rpx;
  background-color: #fff;
  border-radius: 12rpx;
  display: flex;
  padding: 30rpx 46rpx 54rpx;
  justify-content: space-between;
  box-sizing: border-box;

  view {
    font-weight: 400;
    box-sizing: border-box;
    font-size: 32rpx;
    line-height: 45rpx;
    border-radius: 8rpx;
    height: 72rpx;
    width: 290rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .cancel {
    border: 2rpx solid #c7c7c7;
    color: #111;
  }
  .confirm {
    background-color: #6eb657;
    color: #ffffff;
  }
}
</style>
