<template>
  <div class="myApproval">
    <van-sticky>
        <!-- <m-header :backUrl="backUrl" :name="name" :isNative="false" :isFixed="false" /> -->
        <van-dropdown-menu active-color="#01C1B5" :close-on-click-outside="false">
            <van-dropdown-item :title="value0" ref="treeSelect">
              <van-tree-select
                :items="items"
                :active-id.sync="activeId"
                :main-active-index.sync="activeIndex"
                @click-item="clickItem"
              />
            </van-dropdown-item>
            <van-dropdown-item v-model="value1" @change="onSearch" :options="option1" />
            <van-dropdown-item v-model="value2" @change="onSearch" :options="option2" />
            <van-dropdown-item title="创建时间" ref="item">
                <van-cell title="开始时间" is-link @click="onChangeDate('showStart')" :value="searchList.startTime"></van-cell>
                <van-cell title="结束时间" is-link @click="onChangeDate('showEnd')" :value="searchList.endTime"></van-cell>
                <div class="btnWrap">
                    <div class="cancelBtn" @click="cancelBtn">重置</div>
                    <div class="okBtn" @click="okBtn">确定</div>
                </div>
            </van-dropdown-item>
        </van-dropdown-menu>

        <search @onSearch="onSearchChange"></search>

        <van-popup v-model="dataForm.status" position="bottom" round :style="{ height: '40%' }">
            <van-datetime-picker
                v-model="dataForm.currentDate"
                :min-date="dataForm.minDate"
                :max-date="dataForm.maxDate"
                :formatter="formatter"
                @cancel="dataForm.status = false"
                type="date"
                @confirm="chioseDate"
            />
        </van-popup>
        <!-- <van-search placeholder="请输入工单标题" background="#ffffff" @search="onSearch" shape="round" show-action v-model="searchList.title">
            <div slot="action" @click="onSearch">搜索</div>
        </van-search> -->
    </van-sticky>

    <!-- 列表 -->
    <div>
      <van-list
        v-model="loading"
        v-if="dataShow"
        key="data"
        :finished="finished"
        style="margin-top: .1rem;"
        :immediate-check="false"
        finished-text="- 没有更多内容 -"
        @load="getList"
      >
        <van-cell-group class="app-item" v-for="(item, index) in dataList" :key="index" @click="onClick(item)">
          <van-cell class="appItem-title" :border="false" style="padding-bottom: 0" :title="item.title" :value="dayjs(item.create_time).format('YYYY-MM-DD HH:mm')"></van-cell>
          <van-cell>
            <template #title>
              <!-- <p>标题:{{ item.title }}</p> -->
              <p>优先级:
                <van-tag size="small" v-if="item.priority == 2" style="background: #fff9f6;vertical-align: text-bottom;" plain type="warning">紧急</van-tag>
                <van-tag size="small" v-if="item.priority == 3" style="background: #fff6f7;vertical-align: text-bottom;" plain type="danger">非常紧急</van-tag>
                <van-tag size="small" v-if="item.priority == 1" style="background: #edfff6;vertical-align: text-bottom;" plain type="success">一般</van-tag>
                <!-- {{ item.priority | statusFilter }} -->
              </p>
              <div class="info van-hairline--top">
                <span>由 <span style="color: #01C1B5">{{ item.creator_name }}</span> 提交</span>
                 <template v-if="item.is_end">
                  <template v-if="item.is_cancel">
                    <van-tag color="#999999" size="medium" plain>已关闭</van-tag>
                  </template>
                  <template v-else>
                    <van-tag color="#FF4444" style="background: #FFFBFB;" size="medium" v-if="item.is_denied" plain>审批拒绝</van-tag>
                    <van-tag color="#00C988" style="background: #F1FCF9" size="medium" v-else plain>审批通过</van-tag>
                  </template>
                </template>
                <template v-else>
                  <p class="orangeStatus" style="display: flex;" v-if="item.principals">
                    <span style="width: 100px;white-space: nowrap;overflow: hidden;display: inline-block;text-overflow: ellipsis;text-align:right;">{{ item.principals }}</span>处理中
                  </p>
                </template>
              </div>
            </template>
          </van-cell>
        </van-cell-group>
      </van-list>
      <m-empty v-else key="data" />
    </div>
  </div>
</template>
<script>
import MHeader from "@/components/MHeader";
import Search from '@/components/Search'
import { getWorkOrderList, classify } from "./api";
import MEmpty from "@/components/MEmpty";
import dayjs from "dayjs";
import setLoading from '@/common/loading'
export default {
  components: { MHeader, MEmpty, Search },
  data() {
    let query = this.$route.query
    return {
      dayjs,
      backUrl: {
        status: true,
        path: '/approval'
      },
      classify: query.classify,
      value1: 0,
      value2: -1,
      option1: [
        { text: '优先级', value: 0 },
        { text: '一般', value: 1 },
        { text: '紧急', value: 2 },
        { text: '非常紧急', value: 3 },
      ],
      option2: [
          { text: '是否结束', value: -1 },
          { text: '是', value: 1 },
          { text: '否', value: 0 }
      ],
      dataForm: {
          // 时间下拉框
          status: false,
          minDate: new Date(2000, 0, 1),
          maxDate: new Date(2025, 10, 1),
          currentDate: new Date(),
      },
      items: [],
      activeIndex: 0,
      value0: '全部',
      activeId: 0,
      searchList: {
        search: null,
        startTime: null,
        endTime: null,
        page: 1,
        per_page: 10,
        classify: query.classify,
        title: null,
      },
      loading: false,
      finished: false,
      dataShow: true,
      dataList: [],
      name:''
    };
  },
  async mounted() {
    let classifyStr = this.classify;
    if (classifyStr == 1) {
      this.name =  "需我审批"
    } else if (classifyStr == 2) {
         this.name = "我发起的"
    } else if (classifyStr == 3) {
         this.name =  "我相关的"
    }
    document.title = this.name
    try {
      let res = await classify()
      let tempList = res.data || []
      let lastArr = [{ text: '全部', children: [{text: '全部', id: 0}] }]
      tempList.forEach((item, index) => {
        lastArr[index + 1] = {
          text: item.name,
          children: []
        }
        if(item.process_list && item.process_list.length > 0) {
          item.process_list.forEach(child => {
            lastArr[index + 1].children.push({
              text: child.name,
              id: child.id
            })
          })
        }
      });
      this.items = lastArr
    } catch(e) {
        //
    }
    setLoading(true)
    await this.getList();
    setLoading(false)
  },
  methods: {
    clickItem(val) {
      this.value0 = val.text;
      this.$refs.treeSelect.toggle();
      this.onSearch()
    },
    onSearchChange(val) {
      this.searchList.search = val
      this.onSearch()
    },
    onSearch() {
      this.dataList = [] // 重置数据
      this.dataShow = true
      this.loading = true
      this.searchList.page = 1
      this.finished = false
      this.getList()
    },
    onClick(item) {
      this.$router.push({
        path: '/ApprovalAction',
        query: {
          // classify: this.classify,
          workOrderId: item.id,
          processId: item.process,
          // title: `${item.creator_name}提交的${item.process_name}`,
          // principals: item.principals + '处理中'
        }
      })
    },
    async getList() {
      let { ...params } = this.searchList;
      params.endTime = params.endTime ? dayjs(params.endTime).format('YYYY-MM-DD') + ' 23:59:59' : null
      params.priority = this.value1 ? this.value1 : null
      params.isEnd = this.value2 != -1 ? this.value2 : null
      params.processId = this.activeId ? this.activeId : null // 分类id
      const userId = sessionStorage.getItem('userId')
      params.userId = userId

      try {
        const res = await getWorkOrderList(params)
        let result = res.data
        this.loading = false
        // 重点这句，判断是不是重复请求了
        if (this.dataList.length > 0 && result.total_page == 1) {
            return;
        }
        let data = result.data || []
        this.dataList.push(...data)
        if(params.page >= Math.ceil(result.total_count / params.per_page)) {
            this.finished = true
        }
        this.searchList.page++
        if(this.dataList.length <= 0) {
            this.dataShow = false
        }
      } catch {
        //
        this.finished = true
      }
    },
    cancelBtn() {
        this.searchList.startTime = null;
        this.searchList.endTime = null;
        this.onSearch()
        this.$refs.item.toggle();
    },
    okBtn() {
        if(this.searchList.startTime || this.searchList.endTime) {
            this.onSearch()
        }
        this.$refs.item.toggle();
    },
    onChangeDate(type) {
        let dataForm = this.dataForm
        let searchList = this.searchList
        if(type == 'showEnd') {
            if(searchList.startTime) {
            dataForm.minDate = new Date(dayjs(searchList.startTime))
            }
            setTimeout(() => {
                dataForm.currentDate = searchList.endTime ? new Date(dayjs(searchList.endTime)) : new Date()
            }, 500)
        } else if(type == 'showStart') {
            dataForm.minDate = new Date(2000, 0, 1)
            setTimeout(() => {
                dataForm.currentDate = searchList.startTime ? new Date(dayjs(searchList.startTime)) : new Date()
            }, 500)
        }
        dataForm.status = true
        dataForm.type = type
    },
    chioseDate(value) {
        let dataForm = this.dataForm
        if(dataForm.type == 'showStart') {
            this.searchList.startTime = dayjs(value).format('YYYY-MM-DD')
            if(this.searchList.endTime && dayjs(value).unix() > dayjs(this.searchList.endTime).unix()) {
            this.searchList.endTime = null
            }
        } else if(dataForm.type == 'showEnd') {
            this.searchList.endTime = dayjs(value).format('YYYY-MM-DD')
        }
        dataForm.status = false
    },
    formatter(type, val) {
      if (type === "year") {
        return `${val}年`;
      } else if (type === "month") {
        return `${val}月`;
      } else if (type == "day") {
        return `${val}日`;
      }
      return val;
    }
  },
  filters: {
    statusFilter(item) {
      const obj = {
        1: "一般",
        2: "紧急",
        3: "非常紧急",
      };
      return obj[item];
    },
  },
};
</script>
<style lang="less" scoped>
@import url("../../assets/commonLess/variable.less");
.myApproval {
  min-height: 100vh;
}
.btnWrap {
  display: flex;
  flex-direction: row;
  .cancelBtn {
    height: 48px;
    line-height: 48px;
    background: #e1f6f4;
    color: @mColor;
    text-align: center;
    width: 100%;
  }
  .okBtn {
    width: 100%;
    height: 48px;
    line-height: 48px;
    background: @mColor;
    color: #fff;
    text-align: center;
  }
}
/deep/.van-dropdown-menu__title {
  font-size: .15rem;
}
/deep/.van-tree-select__item--active {
  color: #01c1b5;
}
/deep/.van-sidebar-item--select::before {
  background-color: #01c1b5;
}

.app-item {
  margin: 0 0.12rem 0.1rem;
  background: @whiteColor;
  border-radius: 0.1rem;
  font-size: 0.13rem;
  .appItem-title {
    /deep/.van-cell__title {
      flex-basis: 65%;
      color: #333;
      font-size: .16rem;
    }
    /deep/.van-cell__value {
      flex-basis: 35%;
    }
  }
  .info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #333;
    font-size: .14rem;
    padding-top: .1rem;
    margin-top: .1rem;
  }
  /deep/.van-cell {
    color: #666666;
  }
}
</style>