<template>
  <div class="status-warpper" v-loading="loading">
    <div
      :class="`status-item ${item.value === '6' ? 'last' : ''}`"
      v-for="item in statusOptions"
      :key="item.value"
    >
      <div class="status-item__header">
        <p style="color:#303133;font-weight: 700;height:20px;line-height: 20px;font-size: 15px">
          {{ item.label }} ·
          {{ tableData[item.value] ? tableData[item.value].length : 0 }}
        </p>
        <i v-if="item.value !== '6'" class="el-icon-arrow-left"></i>
      </div>
      <template v-if="level === '1'">
        <draggable
          v-model="tableData[item.value]"
          tag="div"
          class="board-column-content"
          v-bind="dragOptions"
          group="corse"
          @change="hadnleChange"
          @start="drag = true"
          @end="handleEnd"
        >
          <transition-group type="transition" :name="!drag ? 'flip-list' : null">
            <div
              class="drag-item"
              v-for="(item, index) in tableData[item.value]"
              :key="index"
              @click="getRouter('detail', item.id)"
            >
              <div class="drag-item__header">
                <div class="tag">
                  {{ typeOptions[item.type].textLabel }}
                </div>
                <div class="bugNo">
                  {{ item.bugNo }}
                </div>
              </div>

              <div
                style="
                  font-size: 13px;
                  text-align: justify;
                  line-height: 18px;
                  margin: 8px 0px;
                  color: #000;
                "
              >
                {{ item.title }}
              </div>

              <div class="drag-item__footer">
                <el-tooltip
                  :content="`优先级 : ${
                    levelOptions.find(({ value }) => value === item.level).label
                  }`"
                >
                  <p
                    :style="`color:${
                      levelOptions.find(({ value }) => value === item.level).color
                    }`"
                  >
                    {{ levelOptions.find(({ value }) => value === item.level).label }}
                  </p>
                </el-tooltip>
                <!-- <p>{{item.apply_name}}</p> -->
                <el-tooltip :content="`创建人 : ${item.apply_name}`">
                  <p class="name">{{ item.apply_name }}</p>
                </el-tooltip>
              </div>
            </div>
          </transition-group>
        </draggable>
      </template>

      <template v-else>
        <div
          class="drag-item"
          v-for="(item, index) in tableData[item.value]"
          :key="index"
          @click="getRouter('detail', item.id)"
        >
          <div class="drag-item__header">
            <div class="tag">
              {{ typeOptions[item.type].textLabel }}
            </div>
            <div class="bugNo">
              {{ item.bugNo }}
            </div>
          </div>

          <h3 style=" font-size: 13px;
                  text-align: justify;
                  line-height: 18px;
                  margin: 8px 0px;
                  color: #000;">
            {{ item.title }}
          </h3>
          <div class="drag-item__footer">
            <el-tooltip
              :content="`优先级 : ${
                levelOptions.find(({ value }) => value === item.level).label
              }`"
            >
              <p
                :style="`color:${
                  levelOptions.find(({ value }) => value === item.level).color
                }`"
              >
                {{ levelOptions.find(({ value }) => value === item.level).label }}
              </p>
            </el-tooltip>
            <el-tooltip :content="`创建人 : ${item.apply_name}`">
              <p class="name">{{ item.apply_name }}</p>
            </el-tooltip>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>
<script>
import asyncRequest from "@/apis/service/purchaseAndSale/adjust";
import mixinPage from "@/mixins/elPaginationHandle";
import { mapGetters } from "vuex";
import resToken from "@/mixins/resToken";
import addEdit from "@/components/addEdit";
import draggable from "vuedraggable";

import {
  company_type,
  seachStatus,
  statusOptions,
  levelOptions,
  typeOptions,
  columns,
  Pcolumns,
  parmValue,
} from "@/views/pucColumns";
export default {
  name: "adjust",
  mixins: [mixinPage, resToken],
  components: {
    addEdit,
    draggable,
  },
  computed: {
    //组件SIZE设置
    ...mapGetters(["tablebtnSize", "searchSize", "size", "level"]),
    powers() {
      return this.$store.getters.btnList;
    },
    dragOptions() {
      return {
        animation: 200,
        group: "description",
        disabled: false,
        ghostClass: "ghost",
      };
    },
  },
  data() {
    return {
      drag: false,
      select: "1",
      input: "",
      type: 1,
      company_type,
      seachStatus,
      statusOptions,
      levelOptions,
      typeOptions,
      // 表格 - 列参数
      columns, //超管
      Pcolumns, //普通角色
      showModel1: false,
      loading: true,
      showModel: false,
      isDetail: false,
      modelId: 0,
      parmValue: {},

      // 表格 - 数据
      tableData: [],
      // 表格 - 参数
      table: {
        stripe: true,
        border: true,
        _defaultHeader_: ["setcol"],
      },
      // 表格 - 分页
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0,
      },
    };
  },
  methods: {
    getRouter(toRouter, queryId) {
      if (toRouter && queryId) {
        let model = {
          type: "view",
          id: queryId,
        };
        let item = JSON.parse(JSON.stringify(this.parmValue));
        item.select = this.select;
        item.input = this.input;

        let routerModel = {
          options: item,
          router: this.$route.path,
        };
        model.preModel = JSON.stringify(routerModel);
        this.routeGoto(toRouter, model);
      } else {
        this.$message.warning("暂未找到相关流程！");
      }
    },
    handleEnd(evt) {
      this.drag = false;
    },
    hadnleChange(evt) {
      console.log(evt);
      const { added } = evt;
      if (!added) return;
      const { element, newIndex } = added;

      const afterUpdateStatus = Object.keys(this.tableData).findIndex((key) => {
        const item = this.tableData[key].find((item) => item.bugNo === element.bugNo);
        return !!item;
      });

      if (afterUpdateStatus === -1) return;
      this.onUpdateStatus(element, afterUpdateStatus, element.status, newIndex);
    },
    getRouter(toRouter, queryId) {
      if (toRouter && queryId) {
        let model = {
          type: "view",
          id: queryId,
        };
        let item = JSON.parse(JSON.stringify(this.parmValue));
        item.select = this.select;
        item.input = this.input;

        let routerModel = {
          options: item,
          router: this.$route.path,
        };
        model.preModel = JSON.stringify(routerModel);
        this.routeGoto(toRouter, model);
      } else {
        this.$message.warning("暂未找到相关流程！");
      }
    },
    async onUpdateStatus(updateData, afterUpdateStatus, beforeUpdateStatus, newIndex) {
      const model = JSON.parse(JSON.stringify(updateData));
      const sourceData = JSON.parse(JSON.stringify(this.tableData));
      model.status = String(afterUpdateStatus);
      delete model["can"];
      delete model["company_name"];
      try {
        const { code } = await asyncRequest.update({
          bugNo: model.bugNo,
          company_type: model.company_type,
          deal_id: model.deal_id,
          id: model.id,
          // model_id:model.model_id,
          model_id: Array.isArray(model.model_id) ? model.model_id : [model.model_id],
          level: model.level,
          noteNo: model.noteNo,
          remark: model.remark,
          status: model.status,
          title: model.title,
          type: model.type,
        });

        switch (Number(code)) {
          case 0:
            sourceData[afterUpdateStatus][newIndex].status = afterUpdateStatus;
            break;
          default:
            //更新失败撤回
            this.$message.error(
              `${updateData.bugNo} 状态由"${
                statusOptions.find(({ value }) => value === String(beforeUpdateStatus))
                  .label
              }"更新至"${
                statusOptions.find(({ value }) => value === String(afterUpdateStatus))
                  .label
              }"失败`
            );
            sourceData[afterUpdateStatus].splice(newIndex, 1);
            sourceData[beforeUpdateStatus].push(updateData);
            break;
        }
        this.tableData = sourceData;
      } catch (e) {
        //更新失败撤回
        this.$message.error(
          `${updateData.bugNo} 状态由"${
            statusOptions.find(({ value }) => value === String(beforeUpdateStatus)).label
          }"更新至"${
            statusOptions.find(({ value }) => value === String(afterUpdateStatus)).label
          }"失败`
        );
        sourceData[afterUpdateStatus].splice(newIndex, 1);
        sourceData[beforeUpdateStatus].push(updateData);
        this.tableData = sourceData;
      }
    },
    // 新建/编辑/详情
    openModal(id, isDetail) {
      this.showModel = true;
      this.modelId = id;
      this.isDetail = isDetail;
    },
    setData(dataTransfer) {
      // to avoid Firefox bug
      // Detail see : https://github.com/RubaXa/Sortable/issues/1012
      dataTransfer.setData("Text", "");
    },
    // 时间
    // 刷新表格
    async searchList(parmValue) {
      this.loading = true;
      const { code, data, message } = await asyncRequest.list(parmValue);
      if (code === 0) {
        const { list, count } = data;
        const map = statusOptions.reduce(
          (prev, current) => ({
            ...prev,
            [String(current.value)]: [],
          }),
          {}
        );

        list.forEach((item) => {
          const status = String(item.status);
          if (!map[status]) {
            map[status] = [];
          }
          map[status].push(item);
        });

        this.tableData = map;
        this.$emit("getTotal", Number(count));
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.tableData = [];
        this.pageInfo.total = 0;
      }
      this.loading = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.status-warpper {
  margin-top: 10px;
  display: flex;
  overflow: auto;
  min-height: calc(100vh - 200px);

  .status-item {
    min-width: 200px;
    display: flex;
    flex: 1;
    flex-direction: column;
    margin-right: 8px;

    &.last {
      margin-right: 0px;
    }

    &__header {
      box-sizing: border-box;
      padding-left: 5px;
      // padding-right: 15px;
      font-size: 16px;
      display: flex;
      justify-content: space-between;
    }
  }

  .drag-item {
    width: 100%;
    box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.07);
    background: #ffffff;
    margin-top: 8px;
    border-radius: 5px;
    font-size: 12px;
    padding: 10px;
    cursor: pointer;
    color: #aeb0b6;

    &__header {
      display: flex;
      justify-content: space-between;

      .tag {
        color: #409EFF;
        background: #ecf5ff;
        display: inline-block;
        // border: 1px solid #409EFF;
        width: 32px;
        height: 20px;
        line-height: 19px;
        text-align: center;
        // padding: 2px 3px;
        font-size: 12px;
        border-radius: 5px;
      }
      .bugNo {
        display: inline-block;
        // width: 130px;
        line-height: 20px;
      }
    }

    &__footer {
      display: flex;
      justify-content: space-between;

      .name {
        margin-left: 8px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
}

.board-column-content {
  // border: 10px solid transparent;
  height: calc(100vh - 240px);
  max-height: calc(100vh - 240px);
  overflow: auto;
  display: flex;
  justify-content: flex-start;
  flex-direction: column;
  align-items: center;

  span {
    display: inline-block;
    width: 100%;
    height: 100%;
    overflow: auto;
  }
}

.flip-list-move {
  transition: transform 0.5s;
}

.no-move {
  transition: transform 0s;
}

.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}

.list-group {
  min-height: 20px;
}

.list-group-item {
  cursor: move;
}

.list-group-item i {
  cursor: pointer;
}
</style>
