<template>
  <view>
    <!--导航栏 navbar-->
    <view id="header">
      <u-navbar
        :title="title"
        :border-bottom="false"
        :background="{ backgroundColor: 'whitesmoke' }"
      >
      </u-navbar>
    </view>
    <view
      class="body"
      :style="{ bottom: footerHeight + 'px', top: headerHeight + 'px' }"
    >
      <view class="u-relative">
        <!--        <u-image height="750rpx" :src="`${$IMG_URL}${detail.originalImageCode}`"></u-image>-->
        <view>
          <!--          <image :src="`${$IMG_URL}${detail.originalImageCode}`" mode="heightFix" class="height-750rpx"></image>-->
          <image
            :style="{
              '--src': `url(${$IMG_URL}${detail.originalImageCode})`,
              '--transform': `rotate(${angle}deg)`,
            }"
            src="`${$IMG_URL}${detail.originalImageCode}`"
            mode="heightFix"
            class="height-750rpx view"
          ></image>
        </view>
        <view v-if="!isEdit">
          <view
            class="u-absolute prev"
            @click="routerPush(true)"
            v-if="!isFirst"
            >上一款</view
          >
          <view
            class="u-absolute next"
            @click="routerPush(false)"
            v-if="!isLast"
            >下一款</view
          >
        </view>
        <view
          :class="[!isEdit ? 'hide' : 'active']"
          class="u-absolute step u-p-r-30 u-p-l-30"
        >
          <view class="step-main u-p-r-20 u-p-l-20 u-flex">
            <text class="width_100">{{ angle }}°</text>
            <view class="u-relative u-flex-1">
              <view class="line" id="line">
                <view class="line-center"></view>
                <view
                  class="line-step"
                  id="line-step"
                  :style="{
                    left:
                      ((offset.x - lineOffset.left) / lineWidth) * 100 + '%',
                  }"
                  @touchmove="touchMove"
                  @touchend="touchEnd"
                  @touchstart="touchStart"
                />
              </view>
            </view>
            <text class="u-m-l-24" @click="resetStep">重置</text>
          </view>
        </view>
      </view>
      <view class="">
        <!--可调整部位-->
        <view class="u-m-b-20 bg-fff u-p-r-30 u-p-l-30">
          <view class="title u-flex u-p-t-26 u-p-b-18">
            <view class="title-tip u-m-r-10"></view>
            可调整部位
          </view>
          <view class="overflow u-p-b-24">
            <view
              class="button inline-block"
              :class="[
                activePartIndex === index ? 'active' : '',
                filterPartActive(part) ? 'changed' : '',
              ]"
              @click="partClick(index)"
              v-for="(part, index) in parts"
            >
              {{ part.isMainBodyPart === 1 ? "主身" : `部位${index}` }}
            </view>
          </view>
          <view v-if="isEdit">
            <view class="u-p-b-20">
              <u-search
                placeholder="请输入面料名称"
                v-model="keyword"
                border-color="#e1e1e1"
                height="76"
                bg-color="#fff"
                :show-action="false"
              ></u-search>
            </view>
            <view class="overflow u-p-b-30 u-border-bottom">
              <view
                class="image u-m-r-10"
                @click="triggerSelectedMaterial(color)"
                :class="[selectedMaterial.id === color.id ? 'active' : '']"
                v-for="color in MaterialList"
              >
                <image src="" style="width: 100%; height: 100%"></image>
                <view class="image-tip u-line-1">{{ color.materialName }}</view>
              </view>
            </view>
            <view class="overflow" v-if="selectedMaterialItemColors.length > 0">
              <u-image
                :src="`${$IMG_URL}${item.color}`"
                width="80rpx"
                height="80rpx"
                :class="[activeColor.id === item.id ? 'active' : '']"
                shape="circle"
                @click="setActiveColor(item)"
                :key="item.id"
                v-for="item in selectedMaterialItemColors"
                class="u-m-r-20 inline-block color-item"
              ></u-image>
            </view>
            <view class="u-p-t-30 u-p-b-20 text-right">
              <view
                class="button inline-block button-plain button-plain-default"
                @click="cancelMaterialItem"
                >取消</view
              >
              <view
                @click="setMaterialItem"
                class="button inline-block button-default"
                >确定</view
              >
            </view>
          </view>
        </view>
        <!--颜色选择-->
        <view class="bg-fff u-p-r-30 u-p-l-30">
          <view class="title u-flex u-p-t-26 u-p-b-18">
            <view class="title-tip u-m-r-10"></view>
            颜色选择
          </view>
          <view class="u-border-bottom u-p-b-32">
            <view class="">主图颜色</view>
            <view>
              <view v-if="isEditMode">
                <view
                  class="image u-m-r-10"
                  :class="[
                    activeMainPartBodyColorId === color.mdmMaterialColourId
                      ? 'active'
                      : '',
                  ]"
                  @click="colorSelect(color, selectColorList)"
                  v-for="color in selectColorList"
                >
                  <image
                    :src="`${$IMG_URL}${color.fileCode}`"
                    style="width: 100%; height: 100%"
                    mode="aspectFit"
                  ></image>
                  <view class="image-tip u-line-1">{{ color.colour }}</view>
                </view>
              </view>
              <view v-if="!isEditMode">
                <view class="image u-m-r-10" v-for="color in mainPartBodyColor">
                  <image
                    :src="`${$IMG_URL}${color.fileCode}`"
                    style="width: 100%; height: 100%"
                    mode="aspectFit"
                  ></image>
                  <view class="image-tip u-line-1">{{
                    color.colourApi.describes
                  }}</view>
                </view>
              </view>
            </view>
          </view>
          <view>
            <view class="u-p-t-32">
              其他可选颜色
              <text>(可多选)</text>
            </view>
            <view>
              <view v-if="isEditMode">
                <view
                  class="image u-m-r-10"
                  :class="[
                    mainPartOtherColor
                      .map((item) => item.mdmMaterialColourId)
                      .indexOf(color.mdmMaterialColourId) > -1
                      ? 'active'
                      : '',
                  ]"
                  @click="colorSelects(color, selectColorList)"
                  v-for="color in selectColorList"
                >
                  <image
                    :src="`${$IMG_URL}${color.fileCode}`"
                    style="width: 100%; height: 100%"
                    mode="aspectFit"
                  ></image>
                  <view class="image-tip u-line-1">{{ color.colour }}</view>
                </view>
              </view>
              <view v-if="!isEditMode">
                <view
                  class="image u-m-r-10"
                  v-for="color in mainPartOtherColor"
                >
                  <image
                    :src="`${$IMG_URL}${color.fileCode}`"
                    style="width: 100%; height: 100%"
                    mode="aspectFit"
                  ></image>
                  <view class="image-tip u-line-1">{{
                    color.colourApi.describes
                  }}</view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view id="footer" class="footer">
      <view class="footer-btn">
        <view
          class="button button-default button-plain button-plain--default"
          @click="submit"
          v-if="isEditMode"
        >
          加入待上架
        </view>
        <view
          class="button button-plain button-plain--default"
          v-if="!isEditMode"
          @click="cancel"
        >
          取消上架
        </view>
      </view>
    </view>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
// 点击部位获取对应内容
// 选择颜色 设置选中主色
//
import dom from "@/mixins/dom";
import step from "./mixins/step";
import material from "./mixins/material";

export default {
  name: "createMaterial",
  mixins: [dom, step, material],
  data() {
    return {
      keyword: "",

      isEdit: false,

      detail: {},

      colors: [],
      list: [],

      // 选中物料
      selectedMaterial: {},

      // 选中主色
      mainColor: {},
      // 选中其他颜色
      subColor: [],
      selectedMaterialItem: [],
      selectedMaterialItemColor: {},
      activeColor: {},

      styleLibraryMaterialDTOList: [],

      // 过滤数据
      filteredMaterialColorList: [],

      // activePart: {},
      materialId: "",
      activePartIndex: -1,
      submitData: [],
    };
  },
  computed: {
    // 部位
    parts() {
      return (this.detail.styleLibraryPictureVOList || []).sort((a, b) => {
        return a.isMainBodyPart - b.isMainBodyPart < -1;
      });
    },
    selectedMaterialItemColors() {
      let key = (this.selectedMaterialItem.materialColourVOList || []).map(
        (item) => item.colourId
      );
      return this.colors
        .filter((item) => key.indexOf(item.id) > -1)
        .map((item) => {
          return {
            ...item,
            mdmMaterialColourId: item.id,
            materialId: this.selectedMaterialItem.id,
          };
        });
    },
    index() {
      return this.list.findIndex((item) => item.id === this.detail.id);
    },
    isLast() {
      return this.index === this.list.length - 1;
    },
    isFirst() {
      return this.index === 0;
    },
    isEditMode() {
      return this.detail.putawayStatus === 1;
    },
    // 默认的物料颜色可选
    defaultColorList() {
      let key = (this.materialDetail.materialColourVOList || []).map(
        (item) => item.colourId
      );
      return this.colors
        .filter((item) => key.indexOf(item.id) > -1)
        .map((item) => {
          return {
            ...item,
            materialId: this.materialId,
          };
        });
    },

    // 可选颜色过滤
    selectColorList() {
      // 如果部位是主体 且 存在信息则回填老的数据
      if (this.mainPart.length !== 0) {
        return this.mainPart[0].materialColoursList.map((item) => {
          return {
            ...item,
            colour: item.colourName || item.colour,
            mdmMaterialColourId: item.colourId || item.mdmMaterialColourId,
          };
        });
      } else {
        return this.defaultColorList.map((item) => {
          return {
            ...item,
            mdmMaterialColourId: item.id,
          };
        });
      }
    },
    //
    mainPart() {
      return this.submitData.filter(
        (item) => item.isMainBodyPart === 1 && !item.isDeleted
      );
    },
    // 主图颜色 选中的颜色
    mainPartBodyColor() {
      return this.mainPart.filter((item) => item.type === 1);
    },
    // 主图颜色 其他选中的颜色
    mainPartOtherColor() {
      return this.mainPart.filter((item) => item.type !== 1);
    },
    // 主图颜色 其他选中的颜色
    activeMainPartBodyColorId() {
      return this.mainPartBodyColor[0]?.mdmMaterialColourId;
    },
  },

  created() {
    let { id, materialId } = this.$Route.query;
    this.materialId = materialId;
    this.getItem(id);
    this.getList();

    this.getColors();

    this.getMaterialItem(materialId);
    this.getMaterialList();
  },
  methods: {
    filterPartActive(part) {
      let data = this.submitData.filter(
        (item) => !item.isDeleted && part.id === item.styleLibraryPictureId
      );
      return data.length > 0;
    },
    ontherPartTrigger(color, colors) {
      let $data = this.submitData;
      let activePart = this.parts[this.activePartIndex];
      let index = $data.findIndex(
        (item) => item.styleLibraryPictureId === activePart.id
      );
      if (index > -1) {
        let item = $data[index];
        if (item.id) {
          this.$set($data, index, {
            ...item,
            isDeleted: !$data[index]["isDeleted"],
          });
        } else {
          $data.splice(index, 1);
        }
      }
      $data.push({
        materialColoursList: colors,
        isMainBodyPart: 0,
        type: 0,
        isDeleted: false,
        mdmMaterialId: color.materialId,
        mdmMaterialColourId: color.mdmMaterialColourId,
        styleLibraryPictureId: activePart.id,
        styleLibrayId: activePart.styleLibrayId,
      });
      // if()
      // $data.push({
      //   materialColoursList: colors,
      //   isMainBodyPart: 0,type: 2, isDeleted: false,
      //   mdmMaterialId: color.materialId,
      //   mdmMaterialColourId: color.mdmMaterialColourId,
      //   styleLibraryPictureId: activePart.id,
      //   styleLibrayId: activePart.styleLibrayId,
      // })
    },
    //
    setMaterialItem() {
      if (this.activePartIndex === 0) {
        this.materialDetail = this.selectedMaterialItem;
        this.colorSelect(this.activeColor, this.selectedMaterialItemColors);
      } else {
        this.ontherPartTrigger(
          this.activeColor,
          this.selectedMaterialItemColors
        );
      }
      this.activeColor = {};
      this.isEdit = false;
    },
    cancelMaterialItem() {
      this.isEdit = false;
    },
    setActiveColor(color) {
      this.activeColor = {
        ...color,
        materialId: this.selectedMaterialItem.id,
        mdmMaterialColourId: color.id,
      };
    },
    pageReload() {
      this.$Router.replace({
        path: "pages/material/createMaterial",
        query: this.$Route.query,
      });
    },
    // 加入待上架
    submit() {
      let data = {
        styleLibraryMaterialDTOList: this.submitData,
        styleOrderId: this.detail.styleOrderId,
        styleLibraryId: this.detail.id,
      };
      this.$http("stylelibraryorder.addToShelves", data).then((res) => {
        let { code, msg } = res;
        if (code === 200) {
          this.pageReload();
        } else {
          this.$refs.uToast.show({
            title: msg,
          });
        }
      });
    },
    // 取消上架
    cancel() {
      this.$http("stylelibraryorder.unlisted", {
        id: this.detail.styleOrderId,
      }).then((res) => {
        let { code, msg } = res;
        if (code === 200) {
          this.pageReload();
        } else {
          this.$refs.uToast.show({
            title: msg,
          });
        }
      });
    },
    // 主体颜色选择
    // 判断是否已有主体选择
    // 清除其他可选
    colorSelect(color, colors) {
      let $data = this.submitData;
      let index = $data.findIndex(
        (item) =>
          item.mdmMaterialColourId === color.mdmMaterialColourId &&
          item.type === 1 &&
          item.isMainBodyPart === 1
      );
      if (this.activeMainPartBodyColorId) {
        let index = $data.findIndex(
          (item) =>
            item.mdmMaterialColourId === this.activeMainPartBodyColorId &&
            item.type === 1 &&
            item.isMainBodyPart === 1
        );
        let item = $data[index];
        if (item.id) {
          this.$set($data, index, {
            ...$data[index],
            isDeleted: !$data[index]["isDeleted"],
          });
        } else {
          $data.splice(index, 1);
        }
      }
      // 清除数据
      if (index > -1) {
        let item = $data[index];
        if (item.id) {
          this.$set($data, index, {
            ...$data[index],
            isDeleted: !$data[index]["isDeleted"],
          });
        } else {
          $data.splice(index, 1);
        }
      } else {
        $data.push({
          materialColoursList: colors,
          isMainBodyPart: 1,
          type: 1,
          isDeleted: false,
          mdmMaterialId: color.materialId,
          mdmMaterialColourId: color.mdmMaterialColourId,
          styleLibraryPictureId: this.parts[0].id,
          styleLibrayId: this.parts[0].styleLibrayId,
        });
      }
      this.clearColor(color);
    },
    clearColor(color) {
      let $data = this.submitData;
      let index = $data.findIndex(
        (item) =>
          item.mdmMaterialColourId === color.mdmMaterialColourId &&
          item.type === 2 &&
          item.isMainBodyPart === 1
      );
      if (index > -1) {
        let item = $data[index];
        if (item.id) {
          this.$set($data, index, {
            ...item,
            isDeleted: !$data[index]["isDeleted"],
          });
        } else {
          $data.splice(index, 1);
        }
      }
    },
    colorSelects(color, colors) {
      if (color.mdmMaterialColourId === this.activeMainPartBodyColorId) return;
      let $data = this.submitData;
      let index = $data.findIndex(
        (item) =>
          item.mdmMaterialColourId === color.mdmMaterialColourId &&
          item.type === 0
      );
      // 清除数据
      if (index > -1) {
        let item = $data[index];
        if (item.id) {
          this.$set($data, index, {
            ...$data[index],
            isDeleted: true,
          });
        } else {
          $data.splice(index, 1);
        }
      } else {
        $data.push({
          materialColoursList: colors,
          isMainBodyPart: 1,
          type: 0,
          isDeleted: false,
          mdmMaterialId: color.materialId,
          mdmMaterialColourId: color.mdmMaterialColourId,
          styleLibraryPictureId: this.parts[0].id,
          styleLibrayId: this.parts[0].styleLibrayId,
        });
      }
    },
    triggerSelectedMaterial(item) {
      this.selectedMaterial = item;
      this.getMaterialItem(item.id, (data) => {
        this.selectedMaterialItem = data;
      });
    },
    // 上一款 下一款
    routerPush(isNext) {
      this.$Router.push({
        path: "/pages/material/createMaterial",
        query: {
          materialId: this.materialId,
          id: this.list[isNext ? this.index + 1 : this.index - 1].id,
        },
      });
    },
    // 款式列表
    getList(materialTagIdList = []) {
      this.loadStatus = "loading";
      this.$http("stylelibraryorder.page", {
        styleTag: this.keyword,
        status: 0,
        materialTagIdList,
        size: 999,
        current: 1,
      }).then((res) => {
        let { code, data } = res;
        if (code === 200) {
          if (Object.keys(data).length > 0) {
            this.list = data.records;
          } else {
            this.list = [];
          }
        }
      });
    },
    getItem(id) {
      this.$http("stylelibraryorder.details", id).then((res) => {
        let { code, data } = res;
        if (code === 200) {
          // 过滤出数据

          this.detail = data;
          let parts = (data.styleLibraryPictureVOList || []).sort((a, b) => {
            return a.isMainBodyPart - b.isMainBodyPart < -1;
          });
          let selectedList = parts.reduce((res, item) => {
            let selectItem = item["styleLibraryMaterialVOList"].map(($i) => {
              return {
                ...$i,
                isMainBodyPart: item.isMainBodyPart,
                materialColoursList: item.materialInfo.materialColoursList,
              };
            });
            return res.concat(selectItem);
          }, []);
          this.submitData = selectedList;
          // console.log(selectedList)
        }
      });
    },

    // 获取颜色
    getColors() {
      this.$http("colour.selectColour", { color: "" }).then((res) => {
        let { code, data } = res;
        if (code === 200) {
          this.colors = data;
        }
      });
    },
    // 可调整部位点击时间
    partClick(index) {
      if (!this.isEditMode) return;
      if (this.activePartIndex !== index) {
        this.activeColor = {};
        this.selectedMaterial = {};
      }

      this.activePartIndex = index;
      this.isEdit = true;
    },
  },
};
</script>

<style scoped lang="scss">
.color-item {
  &.active {
    border: 1px solid #dda973;
  }
}
.height-750rpx {
  height: 750rpx;
}
.view {
  position: relative;

  &:after {
    content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    background-image: var(--src);
    transform: var(--transform);
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;
    top: 0;
    left: 0;
    z-index: -1;
  }
}

.bg-fff {
  background: #fff;
}
.width_100 {
  width: 100rpx;
}
.inline-block {
  display: inline-block;
  margin-right: 10rpx;
}
.step {
  width: 100%;
  height: 60rpx;
  bottom: 16rpx;
  left: 0;
  color: #fff;
  &.active {
    opacity: 100%;
  }
  &.hide {
    opacity: 0%;
  }
  &-main {
    background: rgba(0, 0, 0, 0.2);
  }
}
.line {
  height: 6rpx;
  width: 100%;
  background: #fff;
  position: relative;
  &-center {
    border-radius: 50%;
    height: 16rpx;
    width: 16rpx;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-right: -8rpx;
    margin-top: -8rpx;
    background: #fff;
  }
  &-step {
    border-radius: 50%;
    height: 40rpx;
    width: 40rpx;
    position: absolute;
    top: 50%;
    margin-top: -20rpx;
    background: #fff;
    //margin-left: -20rpx;
  }
}

.prev,
.next {
  width: 144rpx;
  height: 88rpx;
  line-height: 88rpx;
  color: #d5aa7a;
  text-align: center;
  font-size: 28rpx;
  box-shadow: 0px 2rpx 8rpx 0px rgba(0, 0, 0, 0.1);
  bottom: 60rpx;
}
.prev {
  border-top-right-radius: 100rpx;
  border-bottom-right-radius: 100rpx;
  left: 0;
}
.next {
  border-top-left-radius: 100rpx;
  border-bottom-left-radius: 100rpx;
  right: 0;
}
.title {
  &-tip {
    width: 8rpx;
    height: 32rpx;
    background: #af8d66;
    border-radius: 6rpx;
  }
}
.image {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  display: inline-block;
  border-radius: 8rpx;
  &-tip {
    text-align: center;
    width: 100%;
    height: 40rpx;
    line-height: 40rpx;
    background: rgba(255, 255, 255, 0.8);
    font-size: 24rpx;
    position: absolute;
    bottom: 0;
    left: 0;
  }
  &.active {
    border: 1px solid #dda973;
  }
}

.button {
  border: 1px solid #333;
  border-radius: 44rpx;
  width: 160rpx;
  height: 64rpx;
  line-height: 64rpx;
  text-align: center;
  &-plain {
    &--default {
      color: #333;
    }
  }
  &-default {
    background: #333;
    color: #fff;
  }
  &.active {
    color: #af8d66;
    border: 1px solid #dda973;
  }
  &.changed {
    color: #af8d66;
  }
}
.body {
  position: absolute;
  background: rgba(239, 239, 239, 0.61);
  width: 100%;
  height: auto;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  overflow-y: auto;
}
.overflow {
  overflow-x: auto;
  white-space: nowrap;
}
.footer {
  position: fixed;
  width: 100%;
  bottom: 0;

  z-index: 998;
  background: #fff;
  box-shadow: 0px -4rpx 6rpx 0px rgba(178, 182, 214, 0.1);
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  .footer-btn {
    padding: 20rpx 60rpx;
    .button {
      border: 1px solid #333;
      border-radius: 44rpx;
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      text-align: center;
      font-size: 34rpx;
      &-default {
        background: #333;
        color: #fff;
      }
    }
  }
}
</style>
