<template>
  <div class="app-container" style="padding-top:15px">
    <div class="filter-container">
      <el-button
        type="primary"
        style="position:absolute;right:50px;margin-top:80px"
        @click="$router.push('/convenience/add')"
        ><i class="el-icon-plus" /> 直接建立工单</el-button
      >
      <div class="title">工单列表</div>
      <div style="margin-bottom:15px;margin-top:15px" />
      <el-radio-group v-model="listQuery.phase">
        <el-radio-button :label="undefined">全部阶段</el-radio-button>
        <el-radio-button label="PENDING_ORDER">待接单</el-radio-button>
        <el-radio-button label="PREREQUISITES">要件准备中</el-radio-button>
        <el-radio-button label="PROCESSING">办理中</el-radio-button>
        <el-radio-button label="FINISH">已办结</el-radio-button>
      </el-radio-group>
      <br />
      <br />
      <el-radio-group v-model="listQuery.status">
        <el-radio-button :label="undefined">全部状态</el-radio-button>
        <el-radio-button label="MINE">我处理</el-radio-button>
        <el-radio-button label="FORWARDED">已转交</el-radio-button>
        <el-radio-button label="FORWARDED_APPLY"
          >转交超限审批中</el-radio-button
        >
        <el-radio-button label="SUBMIT_APPLY">已提交审批</el-radio-button>
        <el-radio-button label="WAIT_APPLY">待我审批</el-radio-button>
      </el-radio-group>
      <br />
      <br />
    </div>

    <div class="convenienceList" v-loading="listLoading">
      <div
        v-for="(item, index) in list"
        :key="item.id"
        class="convenience_item"
        @click="
          $router.push({ path: '/convenience/detail', query: { id: item.id } })
        "
      >
        <div class="convenience_item_title" style="flex:1">
          <i class="icon_list" />
          <div>
            <div class="cTitle">{{ item.eventType.eventName }}</div>
            <div class="createDate">
              {{ item.sponsor | sponsorFilter }}创建于{{
                item.createDate | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
              }}
            </div>
          </div>
        </div>
        <div style="display:flex;flex:2;font-size:14px;color:#787878">
          <div style="flex:1">
            <p>流水号：{{ item.serialNumber }}</p>
            <p>
              阶段：{{ item.phase | phaseFilter }}
              <i
                class="icon_timeout"
                v-if="timers && timers[index].status !== null"
              ></i>
              <span style="color:#ff3000">{{
                timers && timers[index].status === null
                  ? ""
                  : timers && timers[index].status
                  ? "已超时"
                  : "即将超时"
              }}</span>
            </p>
          </div>
          <div style="flex:1">
            <p>
              申办人：{{
                item.residentInformation !== null
                  ? item.residentInformation.name
                  : ""
              }}
            </p>
            <!-- v-if="!isLeader" -->
            <p v-if="listQuery.status!==undefined">
              状态：<span style="color:#ff5a00">{{
                item.statusList[0].status | statusFilter
              }}</span>
            </p>
          </div>
          <div style="flex:1">
            <p>受理人：{{ item.firstResponsiblePerson.name }}</p>
          </div>
          <div
            style="flex:1;align-items: center;justify-items: center;display: flex;"
          >
            <div style="font-size:20px;color:#ff6918">
              <i class="icon_timer" />{{
                (timers && timeFormat(timers[index].time)) || "00:00:00"
              }}
              <div>
                <!-- v-has="!'WORKORDER_ADMIN'" -->
                <el-button
                  v-if="listQuery.status!==undefined&&item.phase === 'PENDING_ORDER'"
                  
                  style="margin-left:44px;font-size:14px;padding:7px 10px;width:70px;margin-top:12px"
                  type="primary"
                  size="mini"
                  @click.stop="handleUpdate(item, 5)"
                  >接单</el-button
                >
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      class="dialog"
      :title="updateType | typeFilter"
      append-to-body
      center
      width="434px"
      :visible.sync="applyDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="preview-container">
        <el-form
          ref="applyForm"
          label-position="top"
          :rules="rules"
          :model="payload"
        >
          <el-form-item
            v-if="updateType === 11 || updateType === 14"
            label="操作对象"
            prop="ids"
          >
            <el-select
              v-model="payload.ids"
              multiple
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in staffOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="payload.remark"
              type="textarea"
              placeholder="请输入"
            />
          </el-form-item>

          <el-form-item
            v-if="updateType === 5"
            label="附件"
            prop="attachmentList"
          >
            <AliOss v-model="payload.attachmentList" multiple />
          </el-form-item>

          <el-form-item v-if="updateType === 13">
            <el-radio-group v-model="payload.approve">
              <el-radio :label="true">通过</el-radio>
              <el-radio :label="false">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="default" @click="applyDialog = false">取消</el-button>
        <el-button type="primary" @click="apply">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import Pagination from "@/components/Pagination";
import { list, listOnlyLook, typeList, update } from "@/api/convenience";
import { parseTime } from "@/utils";
import { staffList } from "@/api/staff";
import AliOss from "@/components/AliOSS/index.vue";

export default {
  components: {
    AliOss
  },
  //   components: { Pagination },
  filters: {
    sponsorFilter(status) {
      const statusMap = {
        SELF: "群众",
        STAFF: "工作人员"
      };
      return statusMap[status];
    },
    phaseFilter(status) {
      const statusMap = {
        PENDING_ORDER: "待接单",
        PREREQUISITES: "要件准备中",
        PROCESSING: "办理中",
        FINISH: "办结"
      };
      return statusMap[status];
    },
    statusFilter(status) {
      const statusMap = {
        MINE: "我处理",
        FORWARDED: "已转交",
        FORWARDED_APPLY: "转交超限审批中",
        SUBMIT_APPLY: "已提交审批",
        WAIT_APPLY: "待审核"
      };
      return statusMap[status];
    },
    typeFilter(status) {
      const statusMap = {
        1: "建立工单",
        2: "撤销工单",
        3: "沟通",
        4: "调整工单类别",
        5: "接单",
        6: "要件齐备",
        7: "办结",
        8: "转交超限审批提交",
        9: "转交超限审批撤销",
        10: "转交超限审批",
        11: "发起审批",
        12: "撤销审批",
        13: "审批操作",
        14: "转交"
      };
      return statusMap[status];
    }
  },
  data() {
    return {
      listLoading: false,
      loading: false,
      list: [],
      total: 0,
      listQuery: {},
      selectType: [],
      types: [],
      rules: {},
      applyDialog: false,
      payload: {
        id: undefined,
        version: undefined,
        ids: undefined,
        remark: undefined,
        attachmentList: undefined,
        approve: undefined,
        evaluation: undefined
      },
      staffOptions: [],
      updateType: undefined,
      listQuery: {
        status: undefined,
        phase: undefined
      },
      msec: 0,
      rules: {
        ids: [{ required: true, message: "请选择操作对象", trigger: "change" }]
      },
      timers: undefined,
      timersInterval: undefined,
      isLeader: false,
      isStatusFilter: false
    };
  },
  watch: {
    "listQuery.phase": {
      // 深度监听，可监听到对象、数组的变化
      handler(val) {
        this.listQuery.phase = val;
        this.getList();
      },
      deep: true // true 深度监听
    },
    "listQuery.status": {
      // 深度监听，可监听到对象、数组的变化
      handler(val) {
        this.listQuery.status = val;
        this.getList();
      },
      deep: true // true 深度监听
    }
  },
  created() {
    this.isLeader = sessionStorage
      .getItem("Permissions")
      .includes("WORKORDER_ADMIN");
      // console.log(this.isLeader);
    this.getList();
    this.getStaffList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      if (this.isLeader) {
        if (this.listQuery.status) {
          list(this.listQuery).then(res => {
            this.list = res.d.records;
            this.listLoading = false;
            clearInterval(this.timersInterval);
            const tempData = res.d.records;
            const now = Date.parse(new Date()).toString() / 1000;
            const arr = [];
            tempData.map((item, index) => {
              let msec = [];
              let obj = {};
              switch (item.phase) {
                case "PENDING_ORDER":
                  // 待接单
                  msec = now - item.createDate;
                  obj = {
                    time: msec,
                    phase: item.phase,
                    status: null
                  };
                  arr.push(obj);
                  break;
                case "PREREQUISITES":
                  // 要件准备
                  msec = now - item.createDate;
                  obj = {
                    time: msec,
                    phase: item.phase,
                    status: null
                  };
                  arr.push(obj);
                  break;
                case "PROCESSING":
                  // 办理中
                  msec = now - item.createDate;
                  obj = {
                    time: msec,
                    phase: item.phase,
                    status: null
                  };
                  arr.push(obj);
                  break;
                case "FINISH":
                  msec =
                    item.acceptanceTime +
                    item.prerequisitesTime +
                    item.finishTime;
                  obj = {
                    time: msec,
                    phase: item.phase,
                    status: null
                  };
                  arr.push(obj);
                  // 办结
                  break;
                default:
                  break;
              }
            });
            if (arr.length > 0) {
              arr.map((item, index) => {
                if (item.phase !== "FINISH") {
                  item.time++;
                  if (this.list[index].phase === "PENDING_ORDER") {
                    if (item.status == null) {
                      if (item.time > 57600) {
                        item.status = false;
                        if (item.time >= 86400) {
                          item.status = true;
                        }
                      }
                    }
                  }
                  if (this.list[index].phase === "PROCESSING") {
                    if (item.status == null) {
                      // &&item.time<this.list[index].eventType.commitmentTimeLimit
                      if (
                        item.time >
                        this.list[index].eventType.timeoutReminder * 3600
                      ) {
                        item.status = false;
                        if (
                          item.time >=
                          this.list[index].eventType.commitmentTimeLimit * 3600
                        ) {
                          item.status = true;
                        }
                      }
                    }
                  }
                }
              });
            }
            this.timers = arr;

            this.timersInterval = setInterval(() => {
              if (arr.length > 0) {
                arr.map((item, index) => {
                  if (item.phase !== "FINISH") {
                    item.time++;
                    if (this.list[index].phase === "PENDING_ORDER") {
                      if (item.status == null) {
                        if (item.time > 57600) {
                          item.status = false;
                          if (item.time >= 86400) {
                            item.status = true;
                          }
                        }
                      }
                    }
                    if (this.list[index].phase === "PROCESSING") {
                      if (item.status == null) {
                        // &&item.time<this.list[index].eventType.commitmentTimeLimit
                        if (
                          item.time >
                          this.list[index].eventType.timeoutReminder * 3600
                        ) {
                          item.status = false;
                          if (
                            item.time >=
                            this.list[index].eventType.commitmentTimeLimit *
                              3600
                          ) {
                            item.status = true;
                          }
                        }
                      }
                    }
                  }
                });
              }
              this.timers = arr;
            }, 1000);
          });
        } else {
          listOnlyLook(this.listQuery).then(res => {
            this.list = res.d.records;
            this.listLoading = false;
            clearInterval(this.timersInterval);
            const tempData = res.d.records;
            const now = Date.parse(new Date()).toString() / 1000;
            const arr = [];
            tempData.map((item, index) => {
              if (item.residentInformation === null) {
                console.log(index);
              }
              let msec = [];
              let obj = {};
              switch (item.phase) {
                case "PENDING_ORDER":
                  // 待接单
                  msec = now - item.createDate;
                  obj = {
                    time: msec,
                    phase: item.phase,
                    status: null
                  };
                  arr.push(obj);
                  break;
                case "PREREQUISITES":
                  // 要件准备
                  msec = now - item.createDate;
                  obj = {
                    time: msec,
                    phase: item.phase,
                    status: null
                  };
                  arr.push(obj);
                  break;
                case "PROCESSING":
                  // 办理中
                  msec = now - item.createDate;
                  obj = {
                    time: msec,
                    phase: item.phase,
                    status: null
                  };
                  arr.push(obj);
                  break;
                case "FINISH":
                  msec =
                    item.acceptanceTime +
                    item.prerequisitesTime +
                    item.finishTime;
                  obj = {
                    time: msec,
                    phase: item.phase,
                    status: null
                  };
                  arr.push(obj);
                  // 办结
                  break;
                default:
                  break;
              }
            });
            if (arr.length > 0) {
              arr.map((item, index) => {
                if (item.phase !== "FINISH") {
                  item.time++;
                  if (this.list[index].phase === "PENDING_ORDER") {
                    if (item.status == null) {
                      if (item.time > 57600) {
                        item.status = false;
                        if (item.time >= 86400) {
                          item.status = true;
                        }
                      }
                    }
                  }
                  if (this.list[index].phase === "PROCESSING") {
                    if (item.status == null) {
                      // &&item.time<this.list[index].eventType.commitmentTimeLimit
                      if (
                        item.time >
                        this.list[index].eventType.timeoutReminder * 3600
                      ) {
                        item.status = false;
                        if (
                          item.time >=
                          this.list[index].eventType.commitmentTimeLimit * 3600
                        ) {
                          item.status = true;
                        }
                      }
                    }
                  }
                }
              });
            }
            this.timers = arr;

            this.timersInterval = setInterval(() => {
              if (arr.length > 0) {
                arr.map((item, index) => {
                  if (item.phase !== "FINISH") {
                    item.time++;
                    if (this.list[index].phase === "PENDING_ORDER") {
                      if (item.status == null) {
                        if (item.time > 57600) {
                          item.status = false;
                          if (item.time >= 86400) {
                            item.status = true;
                          }
                        }
                      }
                    }
                    if (this.list[index].phase === "PROCESSING") {
                      if (item.status == null) {
                        // &&item.time<this.list[index].eventType.commitmentTimeLimit
                        if (
                          item.time >
                          this.list[index].eventType.timeoutReminder * 3600
                        ) {
                          item.status = false;
                          if (
                            item.time >=
                            this.list[index].eventType.commitmentTimeLimit *
                              3600
                          ) {
                            item.status = true;
                          }
                        }
                      }
                    }
                  }
                });
              }
              this.timers = arr;
            }, 1000);
          });
        }
      } else {
        // console.log('else:'+this.isLeader);
        list(this.listQuery).then(res => {
          this.list = res.d.records;
          this.listLoading = false;
          clearInterval(this.timersInterval);
          const tempData = res.d.records;
          const now = Date.parse(new Date()).toString() / 1000;
          const arr = [];
          tempData.map((item, index) => {
            let msec = [];
            let obj = {};
            switch (item.phase) {
              case "PENDING_ORDER":
                // 待接单
                msec = now - item.createDate;
                obj = {
                  time: msec,
                  phase: item.phase,
                  status: null
                };
                arr.push(obj);
                break;
              case "PREREQUISITES":
                // 要件准备
                msec = now - item.createDate;
                obj = {
                  time: msec,
                  phase: item.phase,
                  status: null
                };
                arr.push(obj);
                break;
              case "PROCESSING":
                // 办理中
                msec = now - item.createDate;
                obj = {
                  time: msec,
                  phase: item.phase,
                  status: null
                };
                arr.push(obj);
                break;
              case "FINISH":
                msec =
                  item.acceptanceTime +
                  item.prerequisitesTime +
                  item.finishTime;
                obj = {
                  time: msec,
                  phase: item.phase,
                  status: null
                };
                arr.push(obj);
                // 办结
                break;
              default:
                break;
            }
          });
          if (arr.length > 0) {
            arr.map((item, index) => {
              if (item.phase !== "FINISH") {
                item.time++;
                if (this.list[index].phase === "PENDING_ORDER") {
                  if (item.status == null) {
                    if (item.time > 57600) {
                      item.status = false;
                      if (item.time >= 86400) {
                        item.status = true;
                      }
                    }
                  }
                }
                if (this.list[index].phase === "PROCESSING") {
                  if (item.status == null) {
                    // &&item.time<this.list[index].eventType.commitmentTimeLimit
                    if (
                      item.time >
                      this.list[index].eventType.timeoutReminder * 3600
                    ) {
                      item.status = false;
                      if (
                        item.time >=
                        this.list[index].eventType.commitmentTimeLimit * 3600
                      ) {
                        item.status = true;
                      }
                    }
                  }
                }
              }
            });
          }
          this.timers = arr;

          this.timersInterval = setInterval(() => {
            if (arr.length > 0) {
              arr.map((item, index) => {
                if (item.phase !== "FINISH") {
                  item.time++;
                  if (this.list[index].phase === "PENDING_ORDER") {
                    if (item.status == null) {
                      if (item.time > 57600) {
                        item.status = false;
                        if (item.time >= 86400) {
                          item.status = true;
                        }
                      }
                    }
                  }
                  if (this.list[index].phase === "PROCESSING") {
                    if (item.status == null) {
                      // &&item.time<this.list[index].eventType.commitmentTimeLimit
                      if (
                        item.time >
                        this.list[index].eventType.timeoutReminder * 3600
                      ) {
                        item.status = false;
                        if (
                          item.time >=
                          this.list[index].eventType.commitmentTimeLimit * 3600
                        ) {
                          item.status = true;
                        }
                      }
                    }
                  }
                }
              });
            }
            this.timers = arr;
          }, 1000);
        });
      }
    },
    // getList2() {},
    getTypeList() {
      typeList().then(res => {
        // console.log(res);
      });
    },
    getStaffList() {
      staffList().then(res => {
        res.d.records.map(item => {
          const obj = {
            label: item.name,
            value: item.id
          };
          this.staffOptions.push(obj);
        });
      });
    },
    handleTypeChange() {},
    resetPayload() {
      this.payload = {
        id: undefined,
        version: undefined,
        ids: undefined,
        remark: undefined,
        attachmentList: undefined,
        approve: undefined,
        evaluation: undefined
      };
    },
    handleUpdate(row, type) {
      this.resetPayload();
      this.$nextTick(() => {
        this.$refs.applyForm.clearValidate();
      });
      this.updateType = type;
      this.payload.id = row.id;
      this.payload.version = row.version;
      this.payload.type = type;
      switch (type) {
        case 5:
          this.applyDialog = true;
          break;
        case 6:
          this.applyDialog = true;
          break;
        case 11:
          this.applyDialog = true;
          break;
        case 13:
          this.applyDialog = true;
          break;
        case 14:
          this.applyDialog = true;
          break;
        default:
          this.updateData();
          break;
      }
    },
    updateData() {
      update(this.payload).then(res => {
        if (res.c === 200) {
          this.$notify.success("操作成功");
          this.getList();
        }else{
              this.$notify.error(res.m)
            }
      });
    },
    apply() {
      this.$nextTick(() => {
        this.$refs.applyForm.validate(valid => {
          if (valid) {
            this.updateData();
            this.applyDialog = false;
          }
        });
      }, 100);
    },
    handleFilterPhase(phase, event) {
      if (event.target.tagName === "SPAN") {
        event.target.parentElement.setAttribute(
          "class",
          "el-button el-button--" +
            (phase === undefined ? "primary" : "default") +
            " el-button--medium is-round"
        );
      } else {
        event.target.setAttribute(
          "class",
          "el-button el-button--" +
            (phase === undefined ? "primary" : "default") +
            " el-button--medium is-round"
        );
      }
      this.listQuery.phase = phase;
      this.getList();
    },
    handleFilterStatus(status) {
      this.listQuery.status = status;
      this.getList();
    },
    handlePreview() {},
    handleRemove() {},
    beforeRemove() {},
    handleExceed() {},
    timeFormat(timeStamp) {
      const timeStr = `${
        Math.floor(timeStamp / 3600) < 9
          ? "0" + Math.floor(timeStamp / 3600)
          : Math.floor(timeStamp / 3600)
      }:${
        Math.floor(((timeStamp % 86400) % 3600) / 60) < 9
          ? "0" + Math.floor(((timeStamp % 86400) % 3600) / 60)
          : Math.floor(((timeStamp % 86400) % 3600) / 60)
      }:${
        Math.floor(((timeStamp % 86400) % 3600) % 60) < 9
          ? "0" + Math.floor(((timeStamp % 86400) % 3600) % 60)
          : Math.floor(((timeStamp % 86400) % 3600) % 60)
      }`;
      return timeStr;
    }
  }
};
</script>

<style scope>
.text-warning {
  color: #e6a23c;
}
.tb .el-button {
  margin-bottom: 5px;
}
.app-container .title {
  border-left: 5px solid #1890ff;
  padding-left: 8px;
  font-size: 18px;
  color: #000000;
}
.convenience_item {
  padding: 32px;
  margin-bottom: 10px;
  background-color: #fff;
  border-radius: 4px;
  display: flex;
  cursor: pointer;
}
.convenience_item_title {
  display: flex;
  flex: 1;
  align-items: center;
  line-height: 25px;
}
.cTitle {
  font-size: 18px;
  color: #000000;
}
.convenience_item_title .createDate {
  color: #787878;
  font-size: 14px;
}
.icon_list {
  background: url("./img/icon_list.png") no-repeat;
  background-size: cover;
  display: inline-block;
  width: 52px;
  height: 51px;
  margin-right: 12px;
}
.icon_timer {
  background: url("./img/icon_timer.png") no-repeat;
  background-size: cover;
  display: inline-block;
  width: 18px;
  height: 18px;
  margin-right: 4px;
  vertical-align: baseline;
  margin-left: 24px;
}
.el-radio-button--medium .el-radio-button__inner {
  border-radius: 17px;
  margin-right: 10px;
}
.el-radio-button__inner {
  border: 0;
  font-size: 12px !important;
}
.el-radio-button:first-child .el-radio-button__inner {
  border-radius: 17px;
}
.el-radio-button:last-child .el-radio-button__inner {
  border-radius: 17px;
}
.icon_timeout {
  background: url("./img/icon_timeout.png") no-repeat;
  background-size: cover;
  width: 12px;
  height: 11px;
  display: inline-block;
  margin-right: 5px;
}
</style>
