<template>
  <div>
    <FullPage
      title="工艺路线"
      :list="list"
      @init="init"
      :loading="loading"
      @searchData="init"
      @changePage="changePage"
      @changeSize="changeSize"
      :tableColums="tableColums"
      :tableData="tableData"
      :pageIndex="pageIndex"
      :total="total"
    >
      <div slot="titleButton" style="display: flex">
        <Upload
          name="your_file"
          :show-upload-list="false"
          :headers="headers"
          :on-error="uploadError"
          :on-success="uploadSuccess"
          :action="$store.state.ip + '/api/process_route_index_import'"
        >
          <Button type="success" ghost icon="md-exit" style="margin-right: 10px"
            >批量导入</Button
          >
        </Upload>
        <Button
          @click="exportData"
          type="warning"
          ghost
          icon="md-return-left"
          style="margin-right: 10px"
          >批量导出</Button
        >
        <Button @click="handleAddPL()" type="primary" ghost icon="md-add"
          >新增工艺路线</Button
        >
      </div>
      <div slot="navButton"></div>
      <template slot="set" slot-scope="{ row, index }">
        <div class="table-set">
          <a style="margin: 0 5px" @click="handleSet(row, index, 1)">复制</a>
          <a style="margin: 0 5px" @click="handleSet(row, index, 2)">编辑</a>
          <a style="margin: 0 5px" @click="handleSet(row, index, 3)">查看</a>
          <a style="margin: 0 5px; color: red" @click="handleSet(row, index, 4)"
            >删除</a
          >
        </div>
      </template>
    </FullPage>
    <Modal
      class-name="vertical-center-modal"
      width="1000"
      v-model="showModal"
      :title="isCheck ? '工艺路线详情' : '工艺路线编辑'"
    >
      <div class="modal_process_route">
        <div>
          <span style="width: 100px">id: </span
          ><Input
            v-model="info.id"
            disabled
            placeholder="自动生成"
            style="width: 150px"
            size="small"
          />
        </div>
        <div>
          <span style="width: 100px">工艺路线名称: </span
          ><Input
            v-model="info.title"
            placeholder="请输入工艺路线名称"
            size="small"
            :disabled="isCheck"
            style="width: 250px"
          />
        </div>
      </div>
      <div class="modal_content">
        <div class="modal_content_left">
          <span>已选：</span>
          <SlickList
            :distance="10"
            :lockToContainerEdges="true"
            axis="x,y,xy"
            lockAxis="xy"
            v-model="selectTags"
            class="SortableList"
            @input="getChangeLists"
          >
            <SlickItem
              style="z-index: 9999"
              v-for="(item, key) of selectTags"
              :key="key"
              class="SortableItem"
              :index="key"
            >
              <div class="tag-modal">
                <div class="before">{{ key + 1 }}</div>
                <Tag
                  @on-close="closeTag(key, selectTags, item)"
                  color="primary"
                  type="border"
                  closable
                  >{{ item.title }}</Tag
                >
              </div>
            </SlickItem>
          </SlickList>
        </div>
        <div class="modal_content_right">
          <div
            v-for="(item, index) of info.bps"
            :key="index"
            :label="item.title"
          >
            <div v-for="(_item, _index) in item.cld" :key="_index" >
              <div v-if="_item.cld&&_item.cld.length>0" style="position:relative;left:0;top:0">{{ _item.title }}:</div>
              <Tooltip v-for="(__item, __index) of _item.cld" :key="__index">
                <div slot="content">
                  <p>工时：{{ __item.time }}</p>
                  <p>工价：{{ __item.wages }}</p>
                  <p>产能：{{ __item.capacity }}</p>
                </div>
                <Checkbox
                  @on-change="changeCheck($event, __item, selectTags)"
                  v-model="__item.show"
                  :disabled="isCheck"
                  style="padding: 0px 5px"
                  >{{ __item.title }}</Checkbox
                >
              </Tooltip>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer">
        <Button @click="showModal = false" type="primary" ghost>取消</Button>
        <Button @click="saveTableData()" v-show="!isCheck" type="primary"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import { mapState } from "vuex";
import { SlickList, SlickItem } from "vue-slicksort";
export default {
  name: "ProcessLine",
  components: {
    SlickList,
    SlickItem,
  },
  props: {},
  // import引入的组件需要注入到对象中才能使用
  data() {
    // 这里存放数据
    return {
      list: [
        {
          title: "工艺路线名称",
          name: "Input",
          value: "",
          serverName: "title",
          placeholder: "请输入工艺路线名称",
        },
      ],
      tableColums: [
        {
          title: "序号",
          type: "index",
          align: "center",
          key: "id",
          width: "100",
        },
        { title: "工艺路线名称", align: "center", key: "title" },
        { title: "操作", align: "center", slot: "set", width: "220" },
      ],
      tableData: [],
      pageIndex: 1,
      total: 0,
      pageSize: 10,
      proxyObj: {},
      loading: false,
      showModal: false,
      processRouteId: "",
      processRouteName: "",
      selectTags: [], //已选列表
      headers: { Authorization: localStorage.getItem("token") },
      info: {
        title: "",
        price: "",
        parts_id: "",
        id: null,
        properties: [], //工序号
        procedure: [], //工艺属性id
        list: [],
        bps: [],
        procedure_id: "",
      },
      isCheck: false,
    };
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.axios("/api/bp_list").then((res) => {
      this.info.bps = res.data;
    });
    this.axios("/api/bpp_list").then((res) => {
      res.data.map((v) => {
        if (v.select) {
          v.cld.map((z) => {
            v.select.map((k) => {
              z.show = k == z.id ? true : false;
            });
          });
        } else {
          v.cld.map((v) => (v.show = false));
        }
      });
      this.info.list = res.data;
    });
  },
  methods: {
    handleAddPL() {
      this.isCheck = false;
      this.info.id = "";
      this.info.title = "";
      this.info.procedure_id = "";
      this.selectTags = [];
      for (const key in this.info.bps) {
        const element = this.info.bps[key];
        element.cld.forEach((z) => {
          z.show = false;
        });
      }
      this.showModal = true;
    },
    //1复制 2编辑 3查看 4删除
    handleSet(row, index, type) {
      this.info.id = row.id;
      this.info.title = row.title;
      this.info.procedure_id = row.procedure_id;
      this.selectTags = [];
      const arr = this.info.procedure_id
        ? this.info.procedure_id.split(",")
        : [];
      for (const key in this.info.bps) {
        const el = this.info.bps[key];
        el.cld.forEach((z) => {
          z.show = false;
        });
      }
      this.$nextTick(() => {
        arr.forEach((element) => {
          for (const key in this.info.bps) {
            const el = this.info.bps[key];
            for (const k in el.cld) {
              const e = el.cld[k];
              e.cld &&
                e.cld.forEach((z) => {
                  if (z.id == element) {
                    z.show = true;
                    this.selectTags.push(z);
                  }
                });
            }
          }
        });
        switch (type) {
          case 1:
            this.axios({
              method: "post",
              url: "/api/technological_route_edit",
              data: {
                title: row.title + "副本",
                procedure_id: this.info.procedure_id,
              },
            })
              .then((res) => {
                if (res.code == 200) {
                  this.init(this.proxyObj);
                }
              })
              .catch((err) => {});
            break;
          case 2:
            this.showModal = true;
            this.isCheck = false;
            break;
          case 3:
            this.showModal = true;
            this.isCheck = true;
            break;
          case 4:
            this.$Modal.confirm({
              title: "确认删除？",
              content: "此操作确认后不可恢复，请确认！",
              onOk: () => {
                this.axios({
                  method: "post",
                  url: "/api/technological_route_del",
                  data: {
                    id: row.id,
                  },
                })
                  .then((res) => {
                    this.$Message.success(res.msg);
                    this.getData(this.proxyObj);
                    this.showModal = false;
                  })
                  .catch((err) => {});
              },
              onCancel: () => (this.showModal = false),
            });
            break;
        }
      });
    },
    init(row) {
      this.pageIndex = 1;
      row.page_index = this.pageIndex;
      row.page_size = this.pageSize;
      this.proxyObj = row;
      this.getData(row);
    },
    getData(row) {
      this.loading = true;
      this.axios("/api/technological_route", { params: row }).then((res) => {
        this.loading = false;
        this.tableData = res.data.data;
        this.total = res.data.total;
      });
    },
    getChangeLists(e) {},
    saveTableData() {
      // this.tableData = JSON.parse(JSON.stringify(this.selectTags));
      let temparr = [];
      this.selectTags.forEach((el) => {
        temparr.push(el.id);
      });
      this.axios({
        method: "post",
        url: "/api/technological_route_edit",
        data: {
          id: this.info.id,
          title: this.info.title,
          procedure_id: temparr.join(","),
        },
      })
        .then((res) => {
          this.$Message.success(res.msg);
          this.init(this.proxyObj);
        })
        .catch((err) => {});
    },
    closeTag(key, arr, row) {
      //取消tag标签展示操作并同步下方的复选框ui同步
      if (this.isCheck) {
      } else {
        for (const key in this.info.bps) {
          const element = this.info.bps[key];
          element.cld.map((p) => {
            p.id == row.id ? (p.show = false) : "";
          });
        }
        arr.splice(key, 1);
        return;
        this.info.bps.map((v) => {
          v.cld.map((p) => {
            p.id == row.id ? (p.show = false) : "";
          });
        });
      }
    },
    changeCheck(e, item, selectArray) {
      //复选框选中与非选中同时同步tag标签跟随操作
      item.show = e;
      if (e) {
        selectArray.push(item);
      } else {
        let id = item.id;
        let id_index = selectArray.findIndex((v) => v.id == id);
        selectArray.splice(id_index, 1);
      }
      let temparr = [];
      this.selectTags.forEach((el) => {
        temparr.push(el.id);
      });
    },
    changePage(e) {
      this.pageIndex = e;
      this.proxyObj.page_index = this.pageIndex;
      this.getData(this.proxyObj);
    },
    changeSize(e) {
      this.pageSize = e;
      this.proxyObj.page_size = this.pageSize;
      this.getData(this.proxyObj);
    },
    async exportData() {
      const res = await this.axios("/api/process_route_index_export", {
        params: { ...this.proxyObj, page: 0 },
      });
      if (res.code == 200) {
        let url = `${this.$store.state.ip}/api/storage/${res.data.file}`;
        location.href = url;
      }
    },
    uploadSuccess(res) {
      if (res.code == 200) {
        this.$Message.success(res.msg || "上传成功");
      } else {
        this.$Message.warning(res.msg || "上传失败");
      }
      this.getData(this.proxyObj);
    },
    uploadError(err) {
      this.$Message.error(err.msg || "上传失败");
    },
  },
  // 监听属性 类似于data概念
  computed: {
    ...mapState(["persimissionData"]),
  },
  // 监控data中的数据变化
  watch: {},
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>

<style lang="scss" scoped>
.vertical-center-modal {
  display: flex;
  align-items: center;
  justify-content: center;
  .ivu-modal {
    top: 0;
  }
}

.modal_process_route {
  div {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin: 5px 0;
  }
}
.modal_content {
  display: flex;
  justify-content: space-around;
  .modal_content_left {
    width: 40%;
  }
  .modal_content_right {
    width: 60%;
    max-height: 500px;
    overflow: hidden;
    overflow-y: auto;
  }
}
.tag-modal {
  display: flex;
  align-items: center;
  .before {
    width: 20px;
    background: #3764ff;
    height: 24px;
    border-radius: 5px 0 0 5px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
  }
}
/deep/.ivu-modal-body {
  max-height: 500px;
  overflow: hidden;
  overflow-y: auto;
}
</style>
