<template>
  <view class="objectives-list">
    <view class="search">
      <view class="top-search">
        <view class="search-input">
          <uv-input
            v-model="searchParams.planName"
            :customStyle="customStyle"
            clearable
            shape="circle"
            placeholder="请输入"
            prefixIcon="search"
            prefixIconStyle="font-size: 22px;color: #6eb657"
          ></uv-input>
        </view>
        <view class="search-button" @click="searchFn">搜索</view>
        <uv-icon name="plus-circle" v-if="addFlag" color="#6eb657" size="24" @click="toDetail(1)" />
      </view>
      <view class="search-content">
        <view
          class="search-list"
          @click="searchClick('consigneeId')"
          :class="searchParams.consigneeId ? 'active' : ''"
        >
          <text>承接对象</text>
          <uv-icon
            name="arrow-down-fill"
            :color="searchParams.consigneeId ? '#6eb657' : '#111111'"
            size="14"
          />
        </view>
        <view
          class="search-list"
          @click="searchClick('period')"
          :class="searchParams.period.length ? 'active' : ''"
        >
          <text>目标周期</text>
          <uv-icon
            name="arrow-down-fill"
            :color="searchParams.period.length ? '#6eb657' : '#111111'"
            size="14"
          />
        </view>
      </view>
    </view>

    <view class="list" v-if="hasInfo">
      <view
        class="item"
        v-for="item in listArr"
        :key="item.id"
        @click.stop.prevent.self="detailClick(item.id)"
      >
        <view class="header">
          <view class="title">{{ item.planName }}</view>
          <view class="status">
            <text class="circle"></text>
            <text>{{ getStatusName(item.planState) }}</text>
          </view>
        </view>
        <view class="content">
          <view class="txt">承接对象：{{ item.consigneeInfo.consigneeName }}</view>
          <view class="txt">目标周期：{{ item.planIssue + ' 至 ' + item.planExpiry }}</view>
          <view class="txt">创建日期：{{ item.createTime }}</view>
          <view class="progress">
            <uv-line-progress
              class="pro-two"
              round
              :showText="false"
              :percentage="item.percentage"
              activeColor="#95dc7e"
              inactiveColor="#f8f8f0"
            ></uv-line-progress>
            <text>{{ item.percentage }}%</text>
          </view>
          <view class="txt">{{ item.execScoreValue }}/{{ item.planScore }}</view>
          <view class="btns">
            <view class="btn" @click.stop.prevent.self="approvalFlowchartFn(item)">
              <text>审核节点</text>
            </view>
            <!-- 区域管理员 -->
            <template v-if="isDLSGLY">
              <!-- 分发 -->
              <template v-if="item.parentId == '0' && item.availScore > 0">
                <view class="btn" @click.stop.prevent.self="toDetail(3, item)">
                  <image src="@/static/images/icon/distribute-img.png" class="image" />
                  <text>分发</text>
                </view>
              </template>
            </template>
            <!-- 营销中心 -->
            <template v-if="isYXZX">
              <!-- 审核 -->
              <template v-if="item.planState === 'INIT' && item.parentId == 0">
                <view class="btn" @click.stop.prevent.self="toDetail(2, item)">
                  <image src="@/static/images/icon/review-img.png" class="image" />
                  <text>审核</text>
                </view>
              </template>
            </template>
            <!-- 二级cso -->
            <template v-if="isROLE_SERVICE">
              <!-- 拆解 -->
              <template v-if="!item.planDetails || item.planDetails.detailsState === 'REJECTED'">
                <view class="btn" @click.stop.prevent.self="toDetail(5, item)">
                  <image src="@/static/images/icon/dismantle-img2.png" class="image" />
                  <text>拆解</text>
                </view>
              </template>
            </template>
            <!-- 数据统计 -->
            <template v-if="item.planDetails">
              <view class="btn" @click.stop.prevent.self="toDetail(6, item)">
                <image src="@/static/images/icon/dismantle-img2.png" class="image" />
                <text>数据统计</text>
              </view>
            </template>
            <!-- 编辑按钮 -->
            <template v-if="isYQGLY && item.parentId == '0'">
              <view class="btn" @click.stop.prevent.self="toEdit(item)">
                <text :class="{ disabled: editDisabled(item) }">编辑</text>
              </view>
            </template>
          </view>
        </view>
      </view>
    </view>
    <noData v-else />
    <!-- 选择承接对象 -->
    <uv-picker
      @cancel="pickerCancel"
      :cancelText="searchParams.consigneeId ? '清空' : '取消'"
      ref="pickerRef"
      :columns="csoList"
      keyName="gsmc"
      @confirm="pickerConfim"
    ></uv-picker>
    <!-- 月份范围 -->
    <KDatePicker
      v-model="show"
      type="month"
      is-range
      :confirmText="searchParams.period.length ? '清除' : '确定'"
      @change="getDate"
      formatter="YYYY-MM-DD"
    />
    <approvalFlowchart ref="approvalFlowchartRef" />
  </view>
</template>

<script setup lang="ts">
import noData from '@/components/noData/index.vue'
import { ref } from 'vue'
import { onShow, onReachBottom } from '@dcloudio/uni-app'
import { getListApi, getListDescendant } from '@/service/modules/objectivesList'
import { getDictByNameApi } from '@/service/modules/getDict'
import KDatePicker from '@/components/dateSelect/k-date-picker/KDatePicker.vue'
import { useLoginStore } from '@/store/login'
import approvalFlowchart from './components/approvalFlowchart.vue'

const loginStore = useLoginStore()
let userInfo: any = loginStore.currentUserInfo
const roles: number[] = userInfo.roles

const customStyle = {
  backgroundColor: '#f6f6f6'
}

class Params {
  consigneeId = ''
  period = [] as string[]
  planName = ''
  total = -1
  current = 1
  size = 10
}

const searchParams = ref(new Params())

const hasInfo = ref(true)
const listArr = ref<any[]>([])
const getList = async () => {
  uni.showLoading()
  const res = await getListApi(searchParams.value)
  if (res.code === 0) {
    searchParams.value.total = res.data.total
    res.data.records.forEach((item: any) => {
      if (typeof item.execScoreValue === 'number' && typeof item.planScore === 'number') {
        let value: any = (item.execScoreValue / item.planScore).toFixed(2)
        item.percentage = value * 100
      }
    })
    listArr.value = listArr.value.concat(res.data.records)
    searchParams.value.total = res.data.total
    hasInfo.value = !!listArr.value.length
  } else {
    hasInfo.value = false
  }
  uni.hideLoading()
}
const pickerCancel = () => {
  if (searchParams.value.consigneeId) {
    searchParams.value.consigneeId = ''
    searchFn()
  }
}

onReachBottom(() => {
  if (listArr.value.length === searchParams.value.total) return
  searchParams.value.current++
  getList()
})
const csoList = ref<any[]>([])
const implPlanStateList = ref<any[]>([])
const getDict = async () => {
  getDictByNameApi('impl_plan_state').then((res: any) => (implPlanStateList.value = res.data))
  getListDescendant().then((res: any) => (csoList.value = [res.data]))
}

const getStatusName = (planState: string) => {
  const curr = implPlanStateList.value?.find((item: any) => item.value === planState)
  return curr?.label
}

const detailClick = (id: number) => {
  if (isROLE_SERVICE.value) return
  const searchInfo = JSON.stringify(searchParams.value)
  uni.navigateTo({
    url: `/pages-sub-admin/objectivesDetailList/index?&searchInfo=${searchInfo}&id=${id}`
  })
}

// 营销中心
const isYXZX = ref(false)
// 药企管理员
const isYQGLY = ref(false)
// 区域管理员
const isDLSGLY = ref(false)

// 二级cso
const isROLE_SERVICE = ref(false)

// 判断是否有新增按钮

const addFlag = ref(false)

onShow(() => {
  // 营销中心
  if (roles.includes(38)) {
    isYXZX.value = true
  }
  // 药企管理员
  if (roles.includes(3)) {
    isYQGLY.value = true
    addFlag.value = true
  }
  // 区域管理员
  if (roles.includes(4)) {
    isDLSGLY.value = true
  }
  if (roles.includes(37)) {
    isROLE_SERVICE.value = true
  }
  listArr.value = []
  getDict()
  searchParams.value.current = 1
  getList()
})

const searchFn = () => {
  listArr.value = []
  searchParams.value.current = 1
  getList()
}

const pickerRef = ref()
const show = ref(false)

const searchClick = (type: string) => {
  if (type === 'consigneeId') {
    pickerRef.value.open()
  } else {
    show.value = true
  }
}

const pickerConfim = (e: any) => {
  searchParams.value.consigneeId = e.value[0].deptId
  searchFn()
}

const getDate = (e: any[]) => {
  if (searchParams.value.period.length) {
    searchParams.value.period = []
  } else {
    searchParams.value.period = e
  }
  show.value = false
  searchFn()
}

const approvalFlowchartRef = ref()
const approvalFlowchartFn = (item: any) => {
  approvalFlowchartRef.value.show(item)
}

// type 1: 新增 2：审核 3: 分发 4：分发审核 5：拆解 6：数据统计 7：拆解审核
const toDetail = (type: number, row?: any) => {
  if (type === 1) {
    uni.navigateTo({
      url: `/pages-sub-admin/objectivesAdd/index?&type=${type}`
    })
  } else {
    uni.navigateTo({
      url: `/pages-sub-admin/objectivesAdd/index?&type=${type}&planId=${row?.planId}`
    })
  }
}

const editDisabled = (item: any) => {
  // 下发的一级包状态
  if (item.parentId == 0) {
    if (item.planType === 'ANN') {
      let flag = item.planState === 'INIT' || item.planState === 'REJECTED'
      return !flag
    } else if (item.planType === 'QRT') {
      let flag = item.children && item.children.length > 0
      return flag
    }
  } else {
    let flag = item.planState === 'INIT' || item.planState === 'REJECTED'
    return !flag
  }
}

// 编辑
const toEdit = (item: any) => {
  const flag = editDisabled(item)
  if (flag) return

  const type = item.parentId == 0 ? 1 : 3
  uni.navigateTo({
    url: `/pages-sub-admin/objectivesAdd/index?&type=${type}&btnType=1&planId=${item?.planId}`
  })
}
</script>

<style lang="scss" scoped>
.objectives-list {
  padding: 24rpx 0;
  .search {
    position: fixed;
    width: 750rpx;
    padding: 0 30rpx;
    top: 0;
    height: 150rpx;
    background-color: #fff;
    z-index: 99;
    .top-search {
      display: flex;
      align-items: center;

      .search-input {
        width: 540rpx;
        height: 70rpx;
      }
      .search-button {
        color: #6eb657;
        font-size: 30rpx;
        margin: 0 10px;
        font-weight: 400;
      }
    }
    .search-content {
      margin-top: 24rpx;
      padding-bottom: 10rpx;
      display: flex;
      .search-list {
        display: flex;
        align-content: center;
        margin-right: 64rpx;
        height: 40rpx;
        text {
          font-weight: 500;
          line-height: 40rpx;
          font-size: 28rpx;
          color: #111111;
          margin-right: 8rpx;
        }
      }
      .active text {
        color: #6eb657;
      }
    }
  }

  .list {
    margin-top: 150rpx;
    padding: 0 30rpx;
    .item {
      margin-bottom: 20rpx;
      width: 100%;
      border-radius: 16rpx;
      box-shadow: 0px 2rpx 8rpx 0px rgba(0, 0, 0, 0.2);
      .header {
        background-color: #f8f8f0;
        padding: 26rpx 20rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-top-left-radius: 16rpx;
        border-top-right-radius: 16rpx;
        .title {
          font-size: 32rpx;
          line-height: 45rpx;
          width: 70%;
          font-weight: 500;
          color: #333;
          word-wrap: break-word;
        }
        .status {
          .circle {
            display: block;
            border-radius: 50%;
            background-color: #72b25b;
            margin-right: 10rpx;
            width: 15rpx;
            height: 15rpx;
          }
          display: flex;
          align-items: center;
          color: #72b25b;
        }
      }
      .content {
        padding: 20rpx;
        .txt {
          font-weight: 400;
          color: #999;
          font-size: 22rpx;
          line-height: 30rpx;
          margin-bottom: 16rpx;
        }
        .progress {
          display: flex;
          align-items: center;
          margin-bottom: 8rpx;
          .pro-two {
            width: 80%;
          }
          text {
            margin-left: 10px;
            color: #010101;
            font-size: 26rpx;
            line-height: 36rpx;
          }
        }
        .btns {
          margin-top: 30rpx;
          display: flex;

          .btn {
            display: flex;
            align-items: center;
            height: 34rpx;
            margin-right: 10rpx;

            .image {
              width: 28rpx;
              height: 28rpx;
              margin-right: 12rpx;
            }
            text {
              color: #6eb657;
              font-size: 24rpx;
              line-height: 34rpx;
            }
            .disabled {
              color: #999;
            }
          }
        }
      }
    }
  }
}
</style>
