<template>
  <div style="padding: 20px">
    <el-card shadow="always">
      <template #header>
        <p>{{ title }}</p>
        <vxe-toolbar ref="toolbar" custom print export>
          <template #buttons>
            <div class="selects">
              <el-select
                style="width: 180px"
                filterable
                clearable
                size="small"
                v-model="select.custom_model_id"
              >
                <el-option
                  v-for="item in models"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                ></el-option>
              </el-select>
              <el-select
                style="width: 100px"
                size="small"
                v-model="select.date_type"
              >
                <el-option
                  v-for="item in dataTypes"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
              <el-date-picker
                style="width: 240px"
                value-format="yyyy-MM-dd"
                size="small"
                :value="select.date_range ? select.date_range.split('~') : ''"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                @input="
                  ([start, end]) => (select.date_range = `${start}~${end}`)
                "
              >
              </el-date-picker>
              <el-input
                clearable
                v-model="select.keyword"
                style="width: 160px"
                placeholder="请输入关键词"
                size="small"
              ></el-input>
              <el-button
                icon="el-icon-search"
                type="primary"
                size="small"
                @click="getList"
                >搜索</el-button
              >
            </div>
          </template>
        </vxe-toolbar>
      </template>

      <template #default>
        <div>
          <vxe-table
            ref="table"
            stripe
            style="margin-top: 10px"
            :loading="loading"
            keep-source
            show-overflow
            :column-config="{ resizable: true }"
            :print-config="{}"
            :export-config="{}"
            :expand-config="{
              accordion: true,

            }"
            :custom-config="{ mode: 'popup' }"
            :data="list"
            @cell-dblclick="cellDblclickEvent"
          >
            <vxe-column
              v-if="$route.params.type === 'all'"
              align="center"
              type="checkbox"
              width="40"
              title=""
            ></vxe-column>
            <vxe-column
              min-width="100"
              header-align="center"
              field="title"
              title="工作名称"
            ></vxe-column>
            <vxe-column
              v-if="$route.params.type === 'all'"
              width="80"
              align="center"
              field="id"
              title="流水号"
            ></vxe-column>
            <vxe-column
              width="80"
              title="发起人"
              align="center"
              field="creator.name"
            ></vxe-column>
            <vxe-column
              v-if="$route.params.type !== 'all'"
              width="80"
              title="承办人员"
              align="center"
              field="last_log.user.name"
            ></vxe-column>
            <vxe-column
              header-align="center"
              min-width="140"
              field="custom_model.name"
              title="流程名称"
            ></vxe-column>
            <vxe-column
              v-if="$route.params.type !== 'all'"
              align="center"
              width="140"
              field="current_node.name"
              title="当前节点"
            ></vxe-column>
            <vxe-column
              v-if="$route.params.type !== 'all'"
              title="收藏状态"
              width="90"
              field="my_fav"
              align="center"
            >
              <template #default="{ row }">
                <el-button
                  :type="row.my_fav ? 'success' : 'primary'"
                  size="mini"
                  @click="toggleFav(row)"
                  >{{ row.my_fav ? "已收藏" : "未收藏" }}</el-button
                >
              </template>
            </vxe-column>
            <vxe-column
              width="164"
              field="no"
              align="center"
              title="编号"
            ></vxe-column>
            <vxe-column
              width="200"
              v-if="$route.params.type === 'all'"
              align="center"
              field="created_at"
              title="发起日期"
              :formatter="
                ({ cellValue }) =>
                  $moment(cellValue).format('YYYY-MM-DD HH:mm:ss')
              "
              :export-method="
                ({ row, column, options }) =>
                  $moment(row['created_at']).format('YYYY-MM-DD HH:mm:ss')
              "
            ></vxe-column>
            <vxe-column
              width="80"
              align="center"
              field="status"
              title="当前状态"
              :formatter="({ cellValue }) => myStatus.get(cellValue)"
              :export-method="
                ({ row, column, options }) => myStatus.get(row['status'])
              "
            >
              <template #default="{ row }">
                <el-tag
                  size="mini"
                  :type="statusColor.get(row.status)"
                  effect="dark"
                  >{{ myStatus.get(row.status) }}</el-tag
                >
              </template>
            </vxe-column>
            <template v-if="$store.getters.device === 'mobile'">
              <vxe-column field="m-operate" type="expand" width="60" fixed="left">
                <template #content="{ row }">
                  <div>
                    <template v-if="$route.params.type !== 'all'">
                      <el-button
                        v-if="row.my_log"
                        type="primary"
                        size="mini"
                        @click="handle(row)"
                      >办理</el-button
                      >
                      <el-button
                        plain
                        type="primary"
                        size="mini"
                        @click="copyTo(row)"
                      >抄送</el-button
                      >
                      <el-button
                        v-if="row.can_recall"
                        plain
                        type="danger"
                        size="mini"
                        @click="recall(row)"
                      >撤回</el-button
                      >
                      <el-button
                        v-if="row.can_delete"
                        plain
                        type="danger"
                        size="mini"
                        @click="destroy(row)"
                      >删除</el-button
                      >
                    </template>

                    <el-button plain type="success" size="mini" @click="detail(row)"
                    >查看</el-button
                    >
                  </div>
                </template>
              </vxe-column>
            </template>
            <template v-else>
              <vxe-column
                min-width="280"
                header-align="center"
                field="operate"
                title="操作"
                fixed="right"
              >
                <template #default="{ row }">
                  <template v-if="$route.params.type !== 'all'">
                    <el-button
                      v-if="row.my_log"
                      type="primary"
                      size="mini"
                      @click="handle(row)"
                    >办理</el-button
                    >
                    <el-button
                      plain
                      type="primary"
                      size="mini"
                      @click="copyTo(row)"
                    >抄送</el-button
                    >
                    <el-button
                      v-if="row.can_recall"
                      plain
                      type="danger"
                      size="mini"
                      @click="recall(row)"
                    >撤回</el-button
                    >
                    <el-button
                      v-if="row.can_delete"
                      plain
                      type="danger"
                      size="mini"
                      @click="destroy(row)"
                    >删除</el-button
                    >
                  </template>

                  <el-button plain type="success" size="mini" @click="detail(row)"
                  >查看</el-button
                  >
                </template>
              </vxe-column>
            </template>
          </vxe-table>

          <el-pagination
            style="margin-top: 10px"
            @size-change="
              (e) => {
                select.page_size = e;
                select.page = 1;
                getList();
              }
            "
            @current-change="
              (e) => {
                select.page = e;
                getList();
              }
            "
            :current-page.sync="select.page"
            :page-sizes="[10, 20, 30, 40, 50]"
            :page-size.sync="select.page_size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </template>
    </el-card>

    <share ref="share" :is-show.sync="isShowShare" :flow="pickedFlow"></share>
  </div>
</template>

<script>
import { flowList, toggleFav, destroy, recall, updateFlowTime } from "@/api/flow";
import moment from "moment/moment";
import share from "./components/share.vue";
export default {
  name: "flowList",
  components: {
    share
  },
  data() {
    return {
      myStatus: new Map([
        [-1, "已退回"],
        [0, "办理中"],
        [1, "已完成"],
      ]),
      statusColor: new Map([
        [-1, "warning"],
        [0, ""],
        [1, "success"],
      ]),

      pickerOptions: {
        shortcuts: [
          {
            text: "一年前",
            onClick(picker) {
              picker.$emit("pick", [
                moment().subtract(1, "years").toDate(),
                new Date(),
              ]);
            },
          },
          {
            text: "一月前",
            onClick(picker) {
              picker.$emit("pick", [
                moment().subtract(1, "months").toDate(),
                new Date(),
              ]);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              picker.$emit("pick", [
                moment().subtract(1, "weeks").toDate(),
                new Date(),
              ]);
            },
          },
          {
            text: "一周后",
            onClick(picker) {
              picker.$emit("pick", [
                new Date(),
                moment().add(1, "weeks").toDate(),
              ]);
            },
          },
          {
            text: "一月后",
            onClick(picker) {
              picker.$emit("pick", [
                new Date(),
                moment().add(1, "months").toDate(),
              ]);
            },
          },
          {
            text: "一年后",
            onClick(picker) {
              picker.$emit("pick", [
                new Date(),
                moment().add(1, "years").toDate(),
              ]);
            },
          },
        ],
      },
      select: {
        page: 1,
        page_size: 20,
        sort_name: "",
        sort_type: "",
        keyword: "",
        department_id: "",
        is_fav: "",
        custom_model_id: "",
        date_range: "",
        date_type: "create_date",
      },
      loading: false,
      list: [],
      total: 0,

      title: "",
      models: [],
      dataTypes: [
        {
          value: "create_date",
          label: "录入时间",
        },
        {
          value: "happened_date",
          label: "经办时间",
        },
      ],

      isShowShare: false,
      pickedFlow: {},
    };
  },
  methods: {
    handle(row) {
      this.$router.push(
        `/flow/create?module_id=${row.custom_model.id}&flow_id=${row.id}`
      );
    },

    detail(row) {
      this.$router.push(
        `/flow/detail?module_id=${row.custom_model.id}&flow_id=${row.id}`
      );
    },
    copyTo(row) {
      this.pickedFlow = row;
      this.isShowShare = true;
    },

    async toggleFav(row) {
      try {
        await toggleFav({
          id: row.id,
        });
        await this.getList();
      } catch (err) {}
    },
    async recall(row) {
      try {
        await recall({ id: row.id });
        await this.getList();
      } catch (err) {}
    },
    async destroy(row) {
      try {
        await destroy({ id: row.id });
        await this.getList();
      } catch (err) {}
    },

    async getList() {
      this.loading = true;
      try {
        const res = await flowList(this.$route.params.type, this.select, false);
        console.log(res);
        this.list = res?.data?.data || [];
        this.total = res?.data?.total ?? 0;
        this.models = res.customModels;
        this.title = res.pageTitle;
        this.loading = false;
      } catch (err) {
        console.error(err);
        this.loading = false;
      }
    },

    async cellDblclickEvent({ row, column }) {
      if(this.$store.state.user.username !== 'admin') return
      if(column.field === 'created_at' || column.field === 'updated_at') {
        this.$prompt('请输入时间', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern:  /^(?:19|20)[0-9][0-9]-(?:(?:0[1-9])|(?:1[0-2]))-(?:(?:[0-2][1-9])|(?:[1-3][0-1])) (?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]:[0-5][0-9]$/,
          inputErrorMessage: '时间格式不正确'
        }).then(({ value }) => {
          updateFlowTime({
            id: row.id,
            date: value
          }).then(_ => {
            this.$message.success('更新成功')
            this.getList()
          })
        })
      }
    },
  },
  computed: {
  },
  activated() {
    this.getList();
  },
  created() {
    this.getList();
  },
  mounted() {
    this.$nextTick(() => {
      if (this.$refs["table"] && this.$refs["toolbar"]) {
        this.$refs["table"].connect(this.$refs["toolbar"]);
      }
    });
  },
};
</script>

<style scoped lang="scss">
.selects > * + * {
  margin: 2px 0 2px 6px;
}
</style>
