<template>
  <div class="start-flow__container">
    <PlacedTop :nodeId="'newMatterIndex'"></PlacedTop>
    <NavBar :is-custom="true" @go-back="handleGoBack">
      <template slot="title">新建流程</template>
      <template slot="right">
        <i class="icon-sousuo1" @click="toSearch" style=""></i>
      </template>
    </NavBar>

    <div class="flow_list">
      <van-tabs
        id="vanTabs"
        v-model="active"
        title-active-color="#409EFF"
        color="#409EFF"
        sticky
        :ellipsis="false"
        @change="onChangeTabs"
        :class="categories && categories.length > 4 ? 'van_tab_filter' : ''"
      >
        <van-tab
          v-for="(tab, index) in categories"
          :key="tab.typeId"
          :title="tab.typeName"
        >
          <div
            class="roadWrapper"
            id="newMatterIndex"
            v-if="currentTypeKey == tab.typeId"
          >
            <van-pull-refresh v-model="isDownLoading" @refresh="onRefresh()">
              <van-list
                v-model="loading"
                :finished="finished"
                :immediate-check="false"
                :offset="20"
                @load="onLoad"
              >
                <van-cell
                  v-for="item in itemList"
                  :key="item.id"
                  @click="showItem(item)"
                  center
                  :border="false"
                >
                  <template slot="title">
                    <div class="flow_list_title">
                      <i
                        class="icon-xinjianliucheng1"
                      ></i>
                    </div>
                    <div class="task_list_word">
                      <div class="task_list_name">
                        {{ item.name }}
                      </div>
                      <div class="task_list_time">{{ item.defKey }}</div>
                    </div>
                  </template>
                  <template #right-icon>
                    <i
                      class="icon-collect"
                      :class="[
                        collectedProcess[item.id]
                          ? 'collection'
                          : 'not-collected',
                      ]"
                      @click.stop="
                        handleCollectOrCancelCollect(
                          item.defKey,
                          collectedProcess[item.id] || ''
                        )
                      "
                    ></i>
                  </template>
                </van-cell>
              </van-list>
            </van-pull-refresh>
            <van-collapse
              v-model="activeNames"
              v-if="isProcessShowButton && finished"
              class="pc_process"
            >
              <van-collapse-item
                title="不可使用流程"
                name="PCProcess"
                :border="false"
                :is-link="false"
              >
                <template #title>
                  不可使用流程
                  <i class="van-icon van-icon-arrow van-cell__right-icon"></i>
                </template>
                <van-cell
                  v-for="item in PCitemList"
                  :key="item.id"
                  @click="showItem(item)"
                  center
                  :border="false"
                  class="task_pc"
                >
                  <template slot="title">
                    <div class="flow_list_title">
                      <i
                        class="icon-xinjianliucheng1"
                      ></i>
                    </div>
                    <div class="task_list_word">
                      <div class="task_list_name">
                        {{ item.name }}
                      </div>
                      <div class="task_list_time" style="color: #bfbfbf">
                        {{ item.defKey }}
                      </div>
                    </div>
                  </template>
                  <template #right-icon>
                    <i
                      class="icon-collect"
                      :class="[
                        collectedProcess[item.id]
                          ? 'collection'
                          : 'not-collected',
                      ]"
                      @click.stop="
                        handleCollectOrCancelCollect(
                          item.defKey,
                          collectedProcess[item.id] || ''
                        )
                      "
                    ></i>
                  </template>
                </van-cell>
              </van-collapse-item>
            </van-collapse>
            <van-empty
              v-if="itemList.length == 0 && finished && !isProcessShowButton"
              class="custom-image"
              :image="noDataImage"
              description="暂无内容"
            />
          </div>
        </van-tab>
      </van-tabs>
      <template v-if="categories && categories.length > 4" class="filter">
        <div class="filter-icon">
          <i
            class="icon-draggable"
            @click="showPopup"
          ></i>
        </div>
        <van-popup
          v-model="showCategories"
          position="right"
          :style="{
            height: 'calc(100% - 48px)',
            width: 'calc(80% - 48px)',
            padding: '24px',
          }"
        >
          <van-radio-group class="custom-radio-group" v-model="checkCategories">
            <van-radio
              v-for="(item, index) in categories"
              :name="item.typeId"
              :key="item.typeId"
            >
              {{ item.typeName }}
            </van-radio>
          </van-radio-group>
        </van-popup>
      </template>
    </div>

    <van-popup
      v-model="showSelectStartor"
      position="bottom"
      get-container="body"
      round
    >
      <van-picker
        show-toolbar
        title="选择发起人"
        :columns="leaders"
        value-key="name"
        @cancel="showSelectStartor = false"
        @confirm="handerStartor"
      />
    </van-popup>
  </div>
</template>
<script>
  const PlacedTop = () => import('@/components/PlacedTop.vue')
  import flow from '@/api/flow.js'
  import {
    myMobileProcessShowButton,
    getMyMobileOftenFlowShowButton,
    myCollectShowButton,
  } from '@/api/flow.js'
  import collectProcess from '@/mixins/collectProcess.js'
  import vanListCommon from '@/mixins/vanListCommon.js'
  import { nest2tile } from '@/utils/array.js'
  import tabActiveMemory from '@/mixins/tabActiveMemory'
  import callBackScroll from '@/mixins/callBackScroll.js'
  import { flowHasStartRights } from '@/api/process.js'
  import { mapState } from 'vuex'
  export default {
    name:'newMatter',
    components: {
      PlacedTop,
    },
    mixins: [collectProcess, vanListCommon, tabActiveMemory,callBackScroll],
    data() {
      return {
        active: 0,
        PCitemList: [], //PC端的流程
        showSelectStartor: false,
        leaders: [],
        leaderId: '',
        selectDefId: '',
        categories: [],
        defaultFlow: [],
        showCategories: false,
        checkCategories: '',
        currentTypeKey: 'all',
        activeNames: [],
        isProcessShowButton: false,
        noDataImage: require('@/assets/images/no_data_list.png'),
      }
    },
    computed: {
      ...mapState('login', ['currentUser']),
    },
    watch: {
      currentTypeKey: {
        handler(newval, oldval) {
          if (newval !== oldval) {
            this.activeNames = []
            this.onRefresh()
            this.isMobileProcessShowButton(newval)
          }
        },
        immediate: true,
      },
      checkCategories: {
        handler(val) {
          this.active = this.categories.findIndex((item) => item.typeId == val)
          this.currentTypeKey = this.categories[this.active].typeId || 'all'
          this.showCategories = false
        },
      },
      activeNames: {
        handler(val) {
          if (val && val.length > 0) {
            this.onLoadPCProcess(val)
          }
        },
      },
    },
    methods: {
      async init() {
        //获取移动端流程分类
        await this.getCurUserFlowType()
        await this.getCollectionProcessList()
        this.onChangeTabs()
      },
      onChangeTabs(event) {
        this.currentTypeKey = this.categories[this.active].typeId || 'all'
        this.checkCategories = this.categories[this.active].typeId || 'all'
      },
      //获取移动端流程分类
      getCurUserFlowType() {
        return flow.getCurUserFlowType().then((resp) => {
          let commonFlowType = [
            {
              typeName: '全部流程',
              typeGroupKey: 'all',
              typeKey: 'all',
              typeId: 'all',
            },
            {
              typeName: '常用流程',
              typeGroupKey: 'MOBILE_FLOW_TYPE',
              typeKey: 'default',
              typeId: 'default',
            },
            {
              typeName: '我的收藏',
              typeGroupKey: 'myCollection',
              typeKey: 'myCollection',
              typeId: 'myCollection',
            },
          ]
          let flowType = resp.value
          this.categories = [...commonFlowType, ...flowType]
        })
      },
      /* 获取常用流程 */
      getDefaultFlow() {
        flow.getDefaultFlow().then((resp) => {
          this.itemList = resp.rows
            ? resp.rows.filter((item) => item.supportMobile == 1)
            : []
          this.PCitemList = resp.rows
            ? resp.rows.filter((item) => item.supportMobile != 1)
            : []
          this.loading = false //数据请成功后
          this.isDownLoading = false //数据请成功后
          this.finished = true
        })
      },
      //上拉加载
      //异步请求数据 ，我们的项目时封装好的方法，此处只是调用
      onLoad() {
        let params = {
          pageBean: {
            page: this.page,
            showTotal: true,
          },
          querys: [
            {
              property: 'support_mobile_',
              value: 1,
              group: 'main',
              relation: 'AND',
              operation: 'EQUAL',
            },
          ],
          sorter: [
            {
              property: 'supportMobile',
              direction: 'DESC',
            },
            {
              property: 'createTime',
              direction: 'DESC',
            },
          ],
        }
        if (this.currentTypeKey == 'default') {
          this.getDefaultFlow()
        } else if (this.currentTypeKey == 'myCollection') {
          this.itemList = this.collectedProcessList.filter(
            (item) => item.supportMobile == 1
          )
          this.loading = false //数据请成功后
          this.isDownLoading = false //数据请成功后
          this.finished = true
        } else {
          if (this.currentTypeKey != 'all') {
            params.querys.push({
              property: 'type_id_',
              value: this.currentTypeKey,
              group: 'main',
              relation: 'AND',
              operation: 'EQUAL',
            })
          }
          let _self = this
          flow
            .myMobileProcess(params)
            .then((res) => {
              _self.loadData(res, _self)
            })
            .catch((error) => {})
            .finally(() => {
              _self.isDownLoading = false
            })
        }
      },
      showItem(row) {
        if (row.supportMobile != 1) {
          this.$notify({
            message: '此流程还未设置手机表单',
            background: '#FFEAD9',
            color: '#fff',
          })
          return
        }

        //超级管理员不做判断
        if (
          this.currentTypeKey === 'default' &&
          this.currentUser &&
          this.currentUser.account !== 'admin'
        ) {
          flowHasStartRights(row.defKey).then((data) => {
            if (!data.value) {
              this.$notify({
                type: 'warning',
                message: '暂无流程启动权限，请联系管理员',
              })
            } else {
              this.handleClickProcess(row)
            }
          })
        } else {
          this.handleClickProcess(row)
        }
      },
      handleClickProcess(row) {
        if (!row.leaders || row.leaders.length == 0) {
          this.$router.push({
            path: '/matter/startProcess',
            query: {
              defId: row.defId,
            },
          })
        } else {
          this.leaderId = ''
          this.leaders = []
          let _this = this
          this.selectDefId = row.defId
          row.leaders.forEach((identity) => {
            _this.leaders.push({ id: identity.id, name: identity.name })
          })
          this.showSelectStartor = true
        }
      },
      handleSelectStartorClose() {
        this.showSelectStartor = false
        this.leaderId = ''
        this.selectDefId = ''
      },
      handerStartor(e) {
        this.leaderId = e.id
        if (!this.leaderId) {
          this.$notify({ type: 'danger', message: '请选择发起人' })
        } else {
          this.showSelectStartor = false
          this.$router.push({
            path: '/matter/startProcess',
            query: {
              defId: this.selectDefId,
              leaderId: this.leaderId,
            },
          })
        }
      },
      toSearch() {
        this.$router.push('/matter/newMatter_search')
      },
      showPopup() {
        this.showCategories = true
      },
      async isMobileProcessShowButton() {
        let params = {
          querys: [],
        }
        if (this.currentTypeKey == 'default') {
          let { value } = await getMyMobileOftenFlowShowButton()
          this.isProcessShowButton = value
        } else if (this.currentTypeKey == 'myCollection') {
          let { value } = await myCollectShowButton()
          this.isProcessShowButton = value
        } else {
          if (this.currentTypeKey != 'all') {
            params.querys.push({
              property: 'type_id_',
              value: this.currentTypeKey,
              group: 'main',
              relation: 'AND',
              operation: 'EQUAL',
            })
          }
          let { value } = await myMobileProcessShowButton(params)
          this.isProcessShowButton = value
        }
      },
      async onLoadPCProcess() {
        let params = {
          pageBean: {
            page: 1,
            pageSize: -1,
            showTotal: true,
          },
          querys: [
            {
              property: 'support_mobile_',
              value: 0,
              group: 'main',
              relation: 'AND',
              operation: 'EQUAL',
            },
          ],
          sorter: [
            {
              property: 'supportMobile',
              direction: 'ASC',
            },
            {
              property: 'createTime',
              direction: 'DESC',
            },
          ],
        }
        if (this.currentTypeKey == 'default') {
          this.getDefaultFlow()
        } else if (this.currentTypeKey == 'myCollection') {
          this.PCitemList = this.collectedProcessList.filter(
            (item) => item.supportMobile !== 1
          )
          this.loading = false //数据请成功后
          this.isDownLoading = false //数据请成功后
          this.finished = true
        } else {
          if (this.currentTypeKey != 'all') {
            params.querys.push({
              property: 'type_id_',
              value: this.currentTypeKey,
              group: 'main',
              relation: 'AND',
              operation: 'EQUAL',
            })
          }
          let { rows } = await flow.myMobileProcess(params)
          this.PCitemList = rows
        }
      },
      handleGoBack() {
        const from = this.$route.query.from
        if (from === 'worker') {
          this.$router.push('/worker')
        } else {
          this.$router.push({
            path: '/home',
          })
        }
      },
    },
  }
</script>
<style lang="scss" scoped>
  .flow_list {
    position: relative;
  }
  ::v-deep .van-collapse-item__title {
    .van-cell__title {
      width: 100%;
      text-align: center;
      color: #409eff;
      border: none;
      i {
        color: #409eff;
      }
    }
  }
  ::v-deep .van-collapse-item__content {
    > .van-cell:last-child {
      border: none;
    }
  }
  .van-hairline--top-bottom::after, 
  .van-hairline-unset--top-bottom::after {
    border-width:0;
  }

  .roadWrapper {
    height: calc(#{$vh} - 100px);
    overflow: scroll;
  }
  .van-cell__title {
    width: calc(100vw - 70px);
  }
  .van-cell {
    padding: 16px;
    border-bottom: 0.5px solid #eee;
  }
  ::v-deep .van-tab {
    font-size: 16px;
  }
  .flow_list_title {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    background: rgba(64, 158, 255, 0.1);
    display: flex;
    align-items: center;
    justify-content: center;
    float: left;
    .icon-xinjianliucheng1{
      color: #409eff;
      font-size: 24px
    }
  }
  .task_list {
    display: block;
    padding: 10px 15px 10px 0;
    border-bottom: 1px solid #e9e9e9;
  }
  .task_list_word {
    width: calc(100% - 60px);
    padding-left: 10px;
    float: left;
    min-height: 42px;
  }
  .task_list_name {
    width: 100%;
    font-size: 16px;
    color: $base-text-color;
    word-break: break-all;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    line-height: 20px;
  }
  .task_list_time {
    font-size: 12px;
    font-weight: 400;
    color: #8c8c8c;
    line-height: 20px;
  }
  .selectStartor {
    width: 70%;
    margin-left: 10%;
  }
  ::v-deep .custom-radio-group,
  .custom-checkbox-group {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    // 单选框，复选框文字样式
    .van-radio__label,
    .van-checkbox__label {
      text-align: center;
      margin-left: 0;
      height: 44px;
      width: 116px;
      line-height: 44px;
      font-size: 14px;
      margin-bottom: 16px;
      background-color: #f9f9f9;
      border-radius: 8px;
      flex: 1;
    }

    .van-radio,
    .van-checkbox {
      position: relative;
      border-radius: 4px;
      margin-left: 8px;
      overflow: hidden;
    }

    // 去掉原本的勾选样式
    .van-radio__icon .van-icon,
    .van-checkbox__icon .van-icon {
      border: 0;
      display: none;
    }
    // 选中之后的文字颜色和背景色设置
    .van-radio__icon--checked + .van-radio__label,
    .van-checkbox__icon--checked + .van-checkbox__label {
      color: #fff;
      background-color: #409eff;
    }
  }
  .filter-icon {
    position: absolute;
    top: 0;
    right: 0;
    text-align: center;
    width: 40px;
    height: 40px;
    line-height: 40px;
    box-shadow: -2px 0px 3px 1px rgba(0, 0, 0, 0.15);
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  ::v-deep.van_tab_filter {
    .van-sticky {
      width: calc(100% - 40px);
    }
  }
  ::v-deep .van-tabs__content {
    margin-top: 10px;
  }
  .collection {
    color: #ffae44;
  }
  .not-collected {
    color: #e7ebf0;
  }
  .pc_process ::v-deep .van-collapse-item__content {
    padding: 0;
  }
  .icon-sousuo1{
    font-size: 22px
  }
  .icon-collect{
    font-size:22px;
  }
  .icon-draggable{
    font-size: 18px;
  }
</style>
