<template>
  <view class="content">
    <uni-calendar
      class="uni-calendar--hook"
      :selected="info.selected"
      :showMonth="false"
      @change="change"
    />
    <uni-collapse ref="collapse">
      <uni-collapse-item
        v-for="collapse in collapseList"
        :key="collapse.name"
        :title="collapse.name"
      >
        <view class="content">
          <template v-for="(item, index) in collapse.children">
            <uni-card :key="index" :title="allType[item.type_id] && allType[item.type_id].name">
              <view class="uni-body">
                <view class="detail-item">
                  <view class="detail-label">提交人</view>
                  <view class="detail-value">
                    {{ item.User.CName }}
                  </view>
                </view>
                <view class="detail-item">
                  <view class="detail-label">审核状态</view>
                  <view
                    class="detail-value"
                    :style="{ color: stateColor[item.audit_state] }"
                  >
                    {{ auditState[item.audit_state] }}
                  </view>
                </view>
                <view class="detail-item" v-if="item.audit_state == 3">
                  <view class="detail-label">拒绝原因</view>
                  <view class="detail-value">
                    {{ item.audit_desc }}
                  </view>
                </view>
                <view class="detail-item">
                  <view class="detail-label">工时</view>
                  <view class="detail-value">
                    {{ item.workload }}
                  </view>
                </view>
              </view>
              <view
                v-if="item.audit_state == 1"
                slot="actions"
                class="card-actions"
              >
                <view class="card-actions-item" @click="onHandleAudit(item)">
                  <text class="card-actions-item-text">通过</text>
                </view>
                <view class="card-actions-item" @click="onHandleReject(item)">
                  <text class="card-actions-item-text">拒绝</text>
                </view>
              </view>
            </uni-card>
          </template>
        </view>
      </uni-collapse-item>
    </uni-collapse>

    <uni-popup ref="inputDialog" type="dialog">
      <uni-popup-dialog
        ref="inputClose"
        mode="input"
        title="拒绝原因"
        :value="auditDesc"
        @confirm="dialogInputConfirm"
      ></uni-popup-dialog>
    </uni-popup>
    <uni-popup ref="auditDialog" type="dialog">
      <uni-popup-dialog
        type="info"
        title="提示"
        content="是否确认通过审批"
        @confirm="auditConfirm"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
import {
  queryAuthWorkHours,
  addWorkHours,
  queryProject,
  authWorkload,
} from "@/services/workload";
import moment from "moment";
import { mapState } from "vuex";

export default {
  data() {
    return {
      auditDesc: "",
      info: {
        lunar: true,
        range: true,
        insert: false,
        selected: [],
      },
      currentItem: {},
      projectList: [],
      currentList: [],
      stateColor: {
        1: "#1890ff",
        2: "#a0d911",
        3: "#f5222d",
      },
      auditState: {
        0: "未提审",
        1: "待审核",
        2: "已通过",
        3: "已拒绝",
      },
      day: moment().format("YYYY-MM-DD"),
    };
  },

  onReady() {
    this.init();
  },
  computed: {
    ...mapState(["allType"]),
    collapseList() {
      const projectList = this.projectList;
      let data = {};
      this.currentList.forEach((item) => {
        let pid = item.project_id;
        let name = "";
        if (!data[pid]) {
          if (pid == "0") name = "其他";
          else {
            let find = projectList.find((p) => p.ID == pid);
            if (!find) return;
            name = find.Name;
          }
          data[pid] = {
            id: pid,
            name,
            children: [],
          };
        }
        data[pid].children.push(item);
      });
      let allList = Object.values(data);
      // 将id为0的项 放置到数组最后
      let index = allList.findIndex((item) => item.id == "0");
      if (index != -1) {
        var temp = allList.splice(index, 1);
        allList.push(temp[0]);
      }
      // allList.forEach((item) => {
      //   // 根据type进行分类
      //   const { list, audit } = this.getTableInfo(item.list);
      //   item.list = list;
      //   item.audit = audit;
      // });
      return allList;
    },
  },
  methods: {
    async init() {
      await this.$store.dispatch("getType");
      this.projectList = await queryProject();
      await this.queryAuthWorkHours();
    },
    change(e) {
      this.day = e.fulldate;
      this.currentList = e.extraInfo.list || [];
    },
    getProject(id) {
      let p = this.projectList.find((p) => p.ID == id);
      if (!p) return "";
      return p.Name;
    },
    onHandleReject(item) {
      this.currentItem = item;
      this.$refs.inputDialog.open();
    },
    onHandleAudit(item) {
      this.currentItem = item;
      this.$refs.auditDialog.open();
    },
    async dialogInputConfirm(desc) {
      let item = this.currentItem;
      let params = [
        {
          id: item.id,
          ts: item.ts,
          user_id: item.User.ID,
          workload: item.workload,
          status: 3,
          desc: desc || "",
        },
      ];
      // 保存
      await authWorkload(params);
      await this.queryAuthWorkHours();
    },
    async auditConfirm() {
      let item = this.currentItem;
      let params = [
        {
          id: item.id,
          status: 2,
          desc: "",
        },
      ];

      await authWorkload(params);
      this.queryAuthWorkHours();
      this.$refs.auditDialog.close();
    },
    async queryAuthWorkHours() {
      const user = uni.getStorageSync("user");
      const data = await queryAuthWorkHours({
        user_id: user.ID,
        audit_state: 1,
      });
      let selected = [];
      Object.keys(data).map((day) => {
        let list = data[day];
        let total = 0;
        let canEdit = false;
        list.forEach((item) => {
          if (item.audit_state == 1) {
            total += item.workload;
            canEdit = true;
          }
        });
        selected.push({
          date: day,
          info: total > 0 ? `${total} 小时` : "",
          list: list,
          color: canEdit ? "#e43d33" : "",
        });
        if (this.day == day) {
          this.currentList = list;
        }
      });
      this.info.selected = selected;
    },
    async onSubmit(values) {
      let params = [
        {
          type_id: Number(values.subTypeId),
          comment: "",
          data: [
            {
              project_id: Number(values.projectId),
              workload: 0,
              day: this.day,
            },
          ],
        },
      ];
      // 新增
      await addWorkHours(params);
      this.queryAuthWorkHours();
    },
    showModal() {
      this.$refs.addModal.open();
    },
    getTableInfo(list) {
      let data = {},
        audit = [];
      const allType = this.allType;
      list.forEach((item) => {
        let pid = allType[item.type_id].parent_id;
        if (!pid) return;
        if (!data[pid]) data[pid] = [];
        data[pid].push(item);
        // 判断是否处于待审批状态
        if (item.audit_state == 1) {
          // 保存可审批的项
          audit.push(item);
        }
      });
      let newList = Object.keys(data).map((pid) => ({
        zIndex: 0,
        id: pid,
        type_id: allType[pid].id,
        children: data[pid],
      }));
      return {
        list: newList,
        audit,
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
  padding: 30rpx;
  padding-top: 0;
}
.button {
  margin-right: 20rpx;
}
.card-actions {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  height: 45px;
  border-top: 1px #eee solid;
}
.detail-item {
  margin: 12rpx 0;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .detail-value {
    max-width: 60%;
    text-align: right;
  }
}
</style>
