<template>
  <view class="service-delivery-add">
    <view class="message">
      <uv-text
        type="error"
        text="本系统中的年度服务目标、【年度服务预算】、年度服务计划等，无论是否经由一方或双方同意或者确认，均不构成双方之间的协议；服务量、服务费用价格与金额等应以另行签署的合同为准。"
      ></uv-text>
    </view>
    <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="belongDate"
          borderBottom
          @click="showSelect('belongDate')"
          required
        >
          <uv-input
            prefixIcon="calendar"
            prefixIconStyle="font-size: 22px;color: #909399"
            v-model="form.belongDate"
            border="none"
            placeholder="请选择"
            readonly
          />
        </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="planIdLabel"
          borderBottom
          @click="showSelect('planIdLabel')"
          required
        >
          <uv-input v-model="form.planIdLabel" border="none" placeholder="请选择" readonly />
          <template v-slot:right>
            <uv-icon name="arrow-right"></uv-icon>
          </template>
        </uv-form-item>
        <uv-form-item label="承接对象" prop="acceptSugLabel" borderBottom required>
          <uv-input v-model="form.acceptSugLabel" border="none" placeholder="请选择" readonly />
        </uv-form-item>
        <uv-form-item label="生效日期" prop="startTime" borderBottom required>
          <uv-input v-model="form.startTime" border="none" placeholder="请选择" readonly />
        </uv-form-item>
        <uv-form-item label="截止日期" prop="endTimeValue" borderBottom required>
          <uv-input v-model="form.endTimeValue" 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="drugtableLabel" borderBottom>
          <uv-input v-model="form.drugtableLabel" border="none" placeholder="请选择" readonly />
        </uv-form-item>
        <!-- 服务区域 -->
        <uv-form-item
          v-if="IS_DLS"
          label="服务区域"
          prop="planIdLabel"
          borderBottom
          @click="showSelect('provAbbr')"
          required
        >
          <uv-input v-model="form.provAbbr" border="none" placeholder="请选择" readonly />
          <template v-slot:right>
            <uv-icon name="arrow-right"></uv-icon>
          </template>
        </uv-form-item>

        <uv-form-item label="有效任务类型如下：" labelWidth="140" labelPosition="top" placeholder>
          <template v-if="!IS_DLS">
            <taskTree ref="taskTreeRef" />
          </template>
          <template v-else>
            <TableData ref="tableRef" />
          </template>
        </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>

      <!-- 选择服务企业 -->
      <uv-picker
        ref="csoPickerRef"
        :columns="[csoList]"
        keyName="name"
        @confirm="(e: any) => pickerConfim(e, 'relatedServiceLabel')"
      ></uv-picker>
      <!-- 选择关联执行包 -->
      <uv-picker
        ref="relationPickerRef"
        :columns="[gljfbOptionsList]"
        keyName="relationScoreName"
        @confirm="(e: any) => pickerConfim(e, 'relationScoreIdLable')"
      ></uv-picker>
      <!-- 选择服务目标 -->
      <uv-picker
        ref="planPickerRef"
        :columns="[planList]"
        keyName="planName"
        @confirm="(e: any) => pickerConfim(e, 'planIdLabel')"
      ></uv-picker>
      <!-- 选择区域 -->
      <uv-picker
        ref="provAbbrRef"
        :columns="[provAbbrArr]"
        @confirm="(e: any) => pickerConfim(e, 'provAbbrArr')"
      ></uv-picker>
    </view>
    <view class="btn" v-if="currentType != 2">
      <view class="cancel" @click="cancelFn">取消</view>
      <view class="confirm" @click="confirmFn">确定</view>
    </view>
  </view>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import KDatePicker from '@/components/dateSelect/k-date-picker/KDatePicker.vue'
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useLoginStore } from '@/store/login'
import {
  getListAncestorApi,
  getPlanListApi,
  selectKfpjfApi,
  wmscorepackageSaveApi,
  getSelectWmScorePackageApi,
  getSelectRelationScoreIdApi,
  wmscorepackageUpdateByIdsApi
} from '@/service/modules/serviceDelivery'
import taskTree from './components/taskTree.vue'
import TableData from './components/TableData.vue'
import { pFlist } from './components/treeList'
import { toRaw } from 'vue'

const loginStore = useLoginStore()

let userInfo: any = loginStore.currentUserInfo
const roles = userInfo.roles
const formDisabled = ref(false)
const editDisabled = ref(false)
const currentType = ref()
const currentId = ref()

const IS_DLS = ref(false)
onLoad(async (e: any) => {
  if (roles.includes(4)) {
    IS_DLS.value = true
  }

  const date = dayjs().format('YYYY-MM')
  form.belongDate = date

  // 获取字典
  getDict()
  currentType.value = e?.type
  currentId.value = e?.id
  if (e?.type === '2') {
    formDisabled.value = true
    initInfo()
  } else if (e?.type == '3') {
    editDisabled.value = true
    initInfo()
  }
})

const initInfo = async () => {
  const obj = {
    scoreId: currentId.value
  }
  const res = await getSelectWmScorePackageApi(obj)
  const detail = res.data
  form.scorePackageName = detail.scorePackageName
  form.belongDate = detail.belongDate
  form.relatedService = detail.relatedService
  form.relatedServiceLabel = detail.relatedServiceName
  form.relationScoreId = detail.relationScoreId
  form.relationScoreIdLable = detail.relationScoreName || '无'
  form.planIdLabel = detail.plan.planName
  form.planId = detail.plan.planId
  form.startTime = detail.startTime
  form.endTimeValue = detail.endTime
  form.acceptSug = detail.acceptSug
  form.acceptSugLabel = detail.acceptSugName
  form.drugtable = detail.drugtable
  form.drugtableLabel = detail?.drugtableName[0]
  form.entTaskLimit = detail.entTaskLimit
  form.description = detail.description
  form.score = detail.score

  if (IS_DLS.value) {
    if (currentType.value === '2') {
      tableRef.value.setData(detail.taskTypeSet)
    } else if (currentType.value === '3') {
      tableRef.value.setData(detail.taskTypeSet)
    }
  } else {
    if (currentType.value === '2') {
      taskTreeRef.value.initData(detail.taskTypeSet)
    } else if (currentType.value === '3') {
      taskTreeRef.value.editData(detail.taskTypeSet)
    }
  }
}

const labelStyle = {
  fontWeight: 400,
  fontSize: '30rpx',
  color: '#000'
}

const csoList = ref<any[]>([])
const planList = ref<any[]>([])
const provAbbrArr = ref<any[]>([])

const planPickerRef = ref()
const csoPickerRef = ref()
const relationPickerRef = ref()
const provAbbrRef = ref()
const planIdLabelFlag = ref(false)
const showSelect = (type: string) => {
  if (formDisabled.value) return
  switch (type) {
    case 'relatedServiceLabel':
      if (roles.includes(3)) return
      if (editDisabled.value) return
      csoPickerRef.value.open()
      break
    case 'relationScoreIdLable':
      if (roles.includes(3)) return
      if (!gljfbOptionsList.value.length) return
      relationPickerRef.value.open()
      break
    case 'planIdLabel':
      if (roles.includes(3) || planIdLabelFlag.value) {
        planPickerRef.value.open()
      }
      break
    case 'provAbbr':
      if (!form.planIdLabel) return
      if (provAbbrArr.value.length) {
        provAbbrRef.value.open()
      }
      break
    default:
      break
  }
}

const tableRef = ref()
const pickerConfim = (e: any, type: string) => {
  if (type === 'relatedServiceLabel') {
    const value = e.value[0]
    form.relationScoreId = ''
    form.relationScoreIdLable = ''
    form.relatedService = value.deptId
    form.relatedServiceLabel = value.name
    initRelationScore(value.deptId)
  }
  if (type === 'relationScoreIdLable') {
    const value = e.value[0]
    form.relationScoreId = value.id
    form.relationScoreIdLable = value.relationScoreName
    initScoreById(value.id)
    planIdLabelFlag.value = true
    getPlanList(value.id)
  }
  if (type === 'planIdLabel') {
    const value = e.value[0]
    form.planId = value.planId
    form.planIdLabel = value.planName
    const curr = selectKfpjfList.value.find((item) => item.deptId == value.consigneeId)
    provAbbrArr.value = curr?.provAbbr?.split(',')

    form.acceptSug = curr?.id
    form.acceptSugLabel = curr?.gsmc
    form.drugtableLabel = value.skuInfo.skuName
    form.drugtable = [value.skuInfo.skuId]
    form.startTime = value.planIssue
    form.endTimeValue = value.planExpiry
    form.score = value.planScore
    if (IS_DLS.value) {
      if (!value.planItems) {
        return uni.showModal({
          title: '提示',
          showCancel: false,
          content: `服务目标【${value.planName}】不存在可用的拆解详情，请核实！`,
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
      tableRef.value.setData(value.planItems, value.planDetails, value.planScore)
      form.score = value?.planDetails?.total + ''
    }
  }
  if (type == 'provAbbrArr') {
    const value = e.value[0]
    console.log('value', value)

    form.provAbbr = value
  }
}

const gljfbOptionsList = ref<any[]>([])
const initRelationScore = async (id: number) => {
  const obj = {
    relatedService: id
  }
  const res = await getSelectRelationScoreIdApi(obj)
  gljfbOptionsList.value = res.data
}

const initScoreById = (id: string) => {
  selectKfpjf(id)
}

const getDict = () => {
  let obj = {
    onlySelf: false
  }
  if (roles.includes(3)) {
    obj.onlySelf = true
  }
  // 获取关联服务企业
  getListAncestorApi(obj).then((res: any) => {
    // 当发包对象为药企管理员
    if (roles.includes(3)) {
      form.relatedServiceLabel = res.data[0].name
      form.relatedService = res.data[0].deptId
      form.relationScoreIdLable = '无'
      form.relationScoreId = '-1'
      selectKfpjf('-1')
      getPlanList(-1)
    }
    csoList.value = res.data
  })
}

const getPlanList = (pkgId: string | number) => {
  getPlanListApi({
    planType: 'QRT',
    pkgId: pkgId
  }).then((res: any) => {
    res.data.forEach((item: any) => {
      item.planName = item.planName + `(${item.planIssue} ~ ${item.planExpiry})`
    })
    planList.value = res.data
  })
}

const selectKfpjfList = ref<any[]>([])
const selectKfpjf = async (id: string) => {
  const res = await selectKfpjfApi({ id })
  const arr = res.data[0].acceptSug.map((item: any) => {
    return {
      gsmc: item.gsmc,
      deptId: item.deptId,
      provAbbr: item.provAbbr,
      id: item.id
    }
  })
  selectKfpjfList.value = arr
  if (!roles.includes(3)) {
    const treeValue = res.data[1].wmScoreTaskTypeList
    taskTreeRef.value.initData(treeValue)
    form.kfpjf = res.data[1].kfpjf
  }
}
const cancelFn = () => {
  uni.navigateBack()
}

const taskTreeRef = ref()
const confirmFn = () => {
  let wmScoreTaskTypeList: any[]
  let pkgTaskTypeQtyList: any[]
  if (!IS_DLS.value) {
    const data = taskTreeRef.value.mapData()
    wmScoreTaskTypeList = [...data]
    data.forEach((item: any) => {
      wmScoreTaskTypeList = wmScoreTaskTypeList.concat(...item.children)
    })
  } else {
    const tableData = tableRef.value.getData()
    pkgTaskTypeQtyList = tableData.map((item: any) => {
      return {
        taskTypeName: item.taskTypeName,
        price: item.score,
        taskTypeId: item.taskTypeId,
        qty: item.qty
      }
    })

    let treeArr = tableData.map((item: any) => {
      return {
        taskTypeName: item.taskTypeName,
        taskTypeId: item.orgTaskTypeId
      }
    })
    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
        })
      }
    })
    wmScoreTaskTypeList = arr.concat(treeArr).filter((item) => {
      if (!item.children || item.children.length > 0) {
        return item
      }
    })
  }

  formRef.value
    .validate()
    .then(async () => {
      if (Number(form.score) > Number(form.kfpjf) && form.relationScoreId != '-1') {
        uni.showToast({
          title: '可分配积分不足',
          icon: 'none'
        })
        return false
      }
      if (IS_DLS.value && !form.provAbbr) {
        return uni.showToast({
          title: '请选择区域',
          icon: 'none'
        })
      }

      form.wmScoreTaskTypeList = wmScoreTaskTypeList
      form.pkgTaskTypeQtyList = pkgTaskTypeQtyList
      form.agentTypeId = form.relationScoreId === '-1' ? '1' : '2'
      form.relationScoreId = form.relationScoreId === '-1' ? '' : form.relationScoreId
      form.kfpjf = form.kfpjf === '' ? '0' : form.kfpjf

      let res
      let text
      if (currentType.value === '1') {
        res = await wmscorepackageSaveApi(form)
        text = '添加成功'
      } else {
        const obj: any = toRaw(form)
        obj.id = currentId
        res = await wmscorepackageUpdateByIdsApi(form)
        text = '编辑成功'
      }
      if (res.code === 0) {
        uni.showToast({
          title: text,
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1000)
      }
    })
    .catch((err: any) => {
      console.log('err', err)
    })
}

const formRef = ref()
const form = reactive({
  scorePackageName: '',
  belongDate: '',
  relatedService: '',
  relatedServiceLabel: '',
  agentTypeId: '',
  relationScoreId: '',
  relationScoreIdLable: '',
  kfpjf: '',
  score: '',
  planId: '',
  planIdLabel: '',
  acceptSug: '',
  acceptSugLabel: '',
  drugtable: [] as any[],
  drugtableLabel: '',
  entTaskLimit: '',
  startTime: '',
  endTimeValue: '',
  provAbbr: '',
  wmScoreTaskTypeList: [] as any[],
  pkgTaskTypeQtyList: [] as any[],
  description: ''
})

const rules = reactive({
  scorePackageName: {
    type: 'string',
    required: true,
    message: '请输入执行包名称',
    trigger: ['blur', 'change']
  },
  belongDate: {
    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']
  },
  planIdLabel: {
    type: 'string',
    required: true,
    message: '请输入执行包名称',
    trigger: ['blur', 'change']
  },
  endTimeValue: {
    type: 'string',
    required: true,
    message: '请选择截止日期',
    trigger: ['blur', 'change']
  },
  acceptSugLabel: {
    type: 'string',
    required: true,
    message: '请选择承接对象',
    trigger: ['blur', 'change']
  },
  provAbbr: {
    type: 'string',
    required: IS_DLS.value,
    message: '请选择服务区域',
    trigger: ['blur', 'change']
  }
})
</script>

<style lang="scss" scoped>
.service-delivery-add {
  background: #f2f2f2;
  min-height: 100vh;
  box-sizing: border-box;
  padding: 24rpx;

  .message {
    background: #fff;
    padding: 30rpx;
    border-radius: 12rpx;
    width: 100%;
    box-sizing: border-box;
  }

  .form {
    margin-top: 20rpx;
    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>
