<template>
  <div class="my-draft card-mode">
    <ht-table
      ref="htTable"
      :data="draftList"
      :page-result="pageResult"
      :selectable="false"
      :quick-search-props="quickSearchProps"
      :default-querys="defaultQuerys"
      :quick-search-width="300"
      :show-export="false"
      pagination-justify="end"
      :show-custom-column="false"
      :card-item-mode="false"
      card-view
      :page-sizes="pageSizes"
      @load="loadData"
    >
      <template #toolbar>
        <el-checkbox
          v-model="checkAll"
          :indeterminate="isIndeterminate"
          @change="handleCheckAllChange"
        >
          全选
        </el-checkbox>
        <el-button
          size="small"
          class="delete-btn"
          :disabled="isDisabled"
          icon="icon-application-delete"
          plain
          @click="handleBatchDelete"
        >
          删除
        </el-button>
      </template>
      <template #search>
        <ht-table-search-panel
          :divide="3"
          :label-width="80"
          display-style="block"
        >
          <ht-table-search-field
            label="标题"
            prop="subject_"
            operation="LIKE"
          />
          <!-- <ht-table-search-field
            label="流程编号"
            prop="bpm_pro_inst.id_"
            operation="LIKE"
          /> -->
          <ht-table-search-field
            label="流程名称"
            prop="proc_def_name_"
            operation="LIKE"
          />
          <ht-table-search-field
            label="创建时间"
            prop="create_time_"
            type="datetimerange"
            operation="BETWEEN"
          />
        </ht-table-search-panel>
      </template>
      <!-- <template #default>
        <ht-table-column type="index" width="50" align="center" label="序号" />
        <ht-table-column label="流程图" width="70">
          <template #default="{ row }">
            <ht-icon
              name="process"
              class="process-icon"
              @click="handleShowFlowChart(row)"
            ></ht-icon>
          </template>
        </ht-table-column>
        <ht-table-column
          align="left"
          prop="id"
          label="流程编号"
          width="200"
          show-overflow-tooltip
        ></ht-table-column>
        <ht-table-column label="标题" align="left">
          <template #default="{ row }">
            <span class="subject" @click="handleClick(row)">
              {{ row.subject }}
            </span>
          </template>
        </ht-table-column>
        <ht-table-column
          align="left"
          prop="procDefName"
          label="流程名称"
          width="160"
          show-overflow-tooltip
        />
        <ht-table-column
          align="left"
          prop="createTime"
          label="创建时间"
          width="160"
          show-overflow-tooltip
        ></ht-table-column>
        <ht-table-column
          label="状态"
          width="160"
          show-overflow-tooltip
          align="left"
        >
          <template #default>
            <span>草稿</span>
          </template>
        </ht-table-column>
      </template>
      <ht-table-column
        v-if="isShowOperation"
        label="操作"
        align="center"
        width="120"
      >
        <template #default="{ row }">
          <el-button type="danger" size="mini" @click="handleDelDraft(row.id)">
            删除草稿
          </el-button>
        </template>
      </ht-table-column> -->
      <template #card="{ data }">
        <ul class="card-content">
          <li
            v-for="item in data"
            :key="item.id"
            class="card-item__wrap card-item"
            :class="{ 'is-checked-item': item.checked }"
          >
            <el-checkbox
              v-model="item.checked"
              @change="(value) => handleCheckbox(value, item)"
            ></el-checkbox>
            <span class="card-item-subject" @click="handleClick(item)">
              {{ item.subject }}
            </span>
            <ht-icon
              class="collection-icon"
              :name="
                collectedProcess[item.procDefId] ? 'collection' : 'NotCollected'
              "
              :class="[
                collectedProcess[item.procDefId]
                  ? 'collection'
                  : 'not-collected',
              ]"
              @click="
                handleCollectOrCancelCollect(
                  item.procDefKey,
                  collectedProcess[item.procDefId] || ''
                )
              "
            ></ht-icon>
            <span class="draft-close-btn" @click="handleDelDraft(item.id)">
              <i class="el-icon-close close"></i>
            </span>
          </li>
        </ul>
      </template>
      <template #empty-card>
        <el-image :src="noDataImg"></el-image>
        <p class="no-data-text">暂无草稿哦</p>
      </template>
    </ht-table>

  </div>
</template>

<script>
  import matter from '@/mixins/matter'
  import tableHeight from '@/mixins/tableHeight'
  import collectProcess from '@/mixins/collectProcess'


  import { getMyRequestList, deleteProcessInstanceById } from '@/api/process'
  import { STATUS_OPTION, DRAFT_QUICK_SEARCH_PROPS } from './const'
  export default {
    name: 'MyDraft',
    components: {

    },
    mixins: [matter, tableHeight, collectProcess],
    data() {
      return {
        draftList: [],
        isShowOperation: false,
        statusOptions: STATUS_OPTION,
        quickSearchProps: DRAFT_QUICK_SEARCH_PROPS,
        defaultQuerys: [
          {
            property: 'status_',
            value: 'draft',
            group: 'status',
            operation: 'LIKE',
            relation: 'AND',
          },
        ],
        loading: false,
        isDisabled: true,
        currentCheckedList: [],
        noDataImg: require('@/assets/nodata_images/no-draft.png'),
        checkAll: false,
        isIndeterminate: false,
      }
    },
    computed: {
      isShowDelBtn() {
        return (row) => {
          const { status, backToStart } = row
          const hasStatus = [
            'revokeToStart',
            'manualend',
            'backToStart',
          ].includes(status)
          return hasStatus || (status === 'back' && backToStart)
        }
      },
    },
    watch: {
      currentCheckedList: {
        handler(val) {
          console.log(val)
          this.checkAll = val.length === this.draftList.length
          this.isIndeterminate =
            val.length > 0 && val.length < this.draftList.length
          if (val.length > 0) {
            this.isDisabled = false
          } else {
            this.isDisabled = true
          }
        },
        deep: true,
      },
    },
    activated() {
      this.$refs.htTable.load(true)
    },
    methods: {
      loadData(param, cb) {
        const data = {
          pageBean: this.pageResult,
          ...param,
          querys: this.getQueryList(param),
          // this.getCurrentQuery(param, 'type_id_'),
        }
        this.getCurrentQuery(data, 'type_id_')
        this.loading = true
        getMyRequestList(data)
          .then((res) => {
            if (!res) return
            const { rows, page, pageSize, total } = res
            this.draftList = rows || []
            this.pageResult = {
              page,
              pageSize,
              total,
            }
          })
          .finally(() => {
            this.loading = false
            cb?.()
          })
      },
      getQueryList(param) {
        let query = param?.querys || []
        if (query?.length > 0) {
          const hasDrafStatus = query.some(
            (item) => item.value === 'draft' && item.property == 'status_'
          )
          if (!hasDrafStatus) {
            query.push({
              property: 'status_',
              value: 'draft',
              group: 'status',
              operation: 'LIKE',
              relation: 'AND',
            })
          }
        } else {
          query = this.defaultQuerys
        }
        if (this.$route.query && this.$route.query.flowKey) {
          query.push({
            property: 'proc_def_key_',
            value: this.$route.query.flowKey,
            operation: 'EQUAL',
            group: 'main',
            relation: 'AND',
          })
        }
        return query
      },
      handleClick(row) {
        this.$router.push({
          path: '/matter/startProcess',
          query: {
            defId: row.procDefId,
            instId: row.id,
            name: row.subject,
            instStatus: row.status,
          },
        })
      },
      handleDelDraft(id) {
        this.$confirm('草稿一经删除则无法恢复，是否确定要删除该草稿?', '提示', {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning',
          closeOnClickModal: false,
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              deleteProcessInstanceById(id).then((res) => {
                if (!res.state) return this.$message.error(res.message)
                instance.confirmButtonLoading = false
                this.$message.success(res.message)
                this.isDisabled = true
                this.$refs.htTable.load()
                this.isIndeterminate = false
                this.checkAll = false
                done()
              })
            } else {
              done()
              instance.confirmButtonLoading = false
            }
          },
        }).then(() => {})
      },
      handleCheckAllChange(val) {
        this.isIndeterminate = false
        this.draftList = this.draftList.map((item) => {
          return {
            ...item,
            checked: val,
          }
        })
        this.handleCheckbox()
      },
      handleCheckbox(value, item) {
        this.currentCheckedList = this.draftList.filter((it) => it.checked)
      },
      handleBatchDelete() {
        const checkedIds = this.currentCheckedList
          .map((item) => item.id)
          ?.join?.(',')
        this.handleDelDraft(checkedIds)
      },
    },
  }
</script>

<style lang="scss" scoped>
  .my-draft {
    height: 100%;
    .subject,
    .process-icon {
      cursor: pointer;
      color: var(--themeColor);
    }
    .card-content {
      .is-checked-item {
        border-color: var(--themeColor);
        box-shadow: 0px 0px 4px rgba(var(--themeColorRgb), 0.65);
      }
      .card-item__wrap {
        position: relative;
        &:hover {
          .draft-close-btn {
            display: block;
          }
        }
      }
      .collection-icon {
        cursor: pointer;
      }
      .collection {
        color: var(--themeColor);
      }
      .not-collected {
        color: rgba($base-dark-title-color, 0.4);
      }
      .card-item-subject {
        cursor: pointer;
        margin-right: 10px;
        margin-left: 26px;
        color: $base-dark-title-color;
      }
      .draft-close-btn {
        cursor: pointer;
        display: none;
        width: 22px;
        height: 22px;
        position: absolute;
        right: -1px;
        top: -1px;
        border-bottom-left-radius: 22px;
        background-color: rgba(var(--themeColorRgb), 0.8);
        // background-color: #0080fe;
        // color: var(--themeColor);
        color: #fff;
        font-size: 16px;
        .close {
          font-size: 12px;
          height: 18px;
          margin-left: 2px;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
    .delete-btn {
      color: $base-color-second-color;
      font-size: 14px;
      margin-left: 24px;
    }
  }
</style>
