<template>
  <div class="peripheral">
    <van-tabs
      :active="active"
      title-active-color="#6600FF"
      color="#6600FF"
      title-inactive-color="#666666"
      line-width="120px"
      @click="changeTopTabs"
    >
      <van-tab title="新增发布">
        <div class="tabs-box">
          <div class="white-box part-1">
            <div class="custom-white-box-content">
              <div class="custom-input-box">
                <input
                  type="text"
                  placeholder="请填写店名"
                  v-model="form.businessName"
                />
              </div>
            </div>
            <ul class="custom-select-list">
              <li
                style="width: 25%"
                v-for="item in quickList"
                v-if="item.value !== ''"
                :key="item.value"
                :class="[
                  quickSleced.value && item.value === quickSleced.value
                    ? 'active'
                    : '',
                ]"
                @click="quickSelect(item)"
              >
                {{ item.label }}
              </li>
            </ul>
          </div>

          <div class="white-box page-2">
            <div class="custom-item-tit">
              <p class="tit">商家地址</p>
            </div>
            <div class="address custom-input-box">
              <input
                type="text"
                v-model="form.businessAddress"
                placeholder="请输入商家地址"
              />
            </div>

            <div class="custom-item-tit">
              <p class="tit">商家电话</p>
            </div>
            <div class="custom-white-box-content">
              <div class="icon-input-box">
                <div class="inp custom-input-box">
                  <input
                    type="text"
                    v-model="form.businessPhone"
                    placeholder="请输入商家电话"
                  />
                </div>
                <div class="icon">
                  <i class="iconfont icon-dianhua1"></i>
                </div>
              </div>
            </div>

            <div class="block-cell-item">
              <div class="custom-item-tit">
                <p class="tit">商家简介</p>
              </div>
              <div class="tit">
                <van-uploader
                  :max-count="12"
                  @delete="deleteFileList"
                  :file-list="fileUrlList"
                  @after-read="afterRead"
                  :show-upload="true"
                >
                </van-uploader>
              </div>
            </div>

            <div class="custom-textarea-box">
              <van-field
                autosize
                type="textarea"
                placeholder="请填写简介"
                :value="form.introduction"
                :maxlength="500"
                show-word-limit
                @change="getIntroduction"
              >
              </van-field>
            </div>
          </div>
        </div>
        <div class="repair-bottom bottom-button" @click="save()">
          <div class="btn">发布</div>
        </div>
      </van-tab>
      <van-tab title="发布记录">
        <div class="tabs-box">
          <van-tabs
            id="activeName"
            :active="activeName"
            color="#6600FF"
            title-active-color="#6600FF"
            title-inactive-color="#666666"
            @change="selectChange"
          >
            <van-tab
              v-if="tabsList.length != 0"
              v-for="item in tabsList"
              :title="item.label"
              :name="item.value"
            >
              <div class="tab-tab-box">
                <div class="tab-tab-card" v-for="item in list">
                  <div class="card-top">
                    <div class="left">
                      <div class="top">{{ item.businessName }}</div>
                      <div class="bottom">入驻时间：{{ item.releaseTime }}</div>
                    </div>
                    <div class="right">
                      <span class="normal-tip z-bg yd">{{ item.type }}</span>

                      <div class="bottom"></div>
                    </div>
                  </div>
                  <div class="card-bottom">
                    <span
                      class="normal-button-app z-bt"
                      v-if="item.source === '2'"
                      @click.stop="editPeripheral(item.id)"
                      >编辑</span
                    >
                    <span
                      class="normal-button-app y-bt"
                      @click.stop="offShelf(item.id)"
                      >下架</span
                    >
                  </div>
                </div>
              </div>
            </van-tab>
          </van-tabs>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>
  
  <script>
// import PositionNav from "@/components/position-nav";
// import Base from "@/pages/base/base";
// import { Dialog, Toast } from "vant";
// import axios from "axios";
import { add, list, edit, getById } from "@/js_sdk/api_periphery.js";
import { getByCodes, getUserLocalStorageInfo } from "@/js_sdk/http.js";
import common from "../../utils/common.js";
// import TelNum from "@/components/tel-number";
// import auth from "@/service/auth";
export default {
  //   components: {
  //     PositionNav,
  //     TelNum,
  //   },
  data() {
    return {
      dc_key: ["periphery_type"],
      active: 0,
      tabActive: "",
      quickSleced: {},
      quickList: [],
      fileList: [],
      activeName: "",
      tabsList: [],
      list: [],
      dic_SelectList: {},
      fileUrlList: [],
      form: {},
      params: {
        pageNum: 1,
        pageSize: 10,
        releaseType: "periphery",
        status: "published",
        type: "",
      },
      totalPage: 1,
    };
  },

  onLoad() {
    // this.active = this.$route.query.active ? this.$route.query.active : 0;
    // this.initDict(this.dc_key).then((res) => {
    //   this.quickList = this.dc_data.periphery_type;
    //   this.tabsList = this.dc_data.periphery_type;
    //   this.selectData();
    // });
    this.getByCodes();
    this.initForm();
  },
  onReachBottom() {
    // this.params.pageNum += 1;
    // this.selectData();
    // console.log("滑动到距离底部100px的时候触发,可以放 。。业务逻辑");
  }, //下拉执行的时候触发 （下拉刷新）
  methods: {
    getIntroduction(e) {
      console.log(e.detail);
      this.form.introduction = e.detail;
    },
    async getByCodes() {
      let that = this;
      let data = await getByCodes(JSON.stringify(this.dc_key));
      that.dic_SelectList = common.handleDicList(data);
      that.quickList = this.dic_SelectList.periphery_type;
      that.tabsList = [
        { label: "全部", value: "" },
        ...this.dic_SelectList.periphery_type,
      ];
      //   that.selectData();
      this.selectData();
    },
    go() {
      this.$common.goBack();
    },

    // addressChange(childValue) {
    //   this.form.businessAddress = childValue;
    // },
    offShelf(id) {
      wx.showModal({
        title: "提示",
        content: "确认下架该信息吗？",
      })
        .then((res) => {
          edit({ id: id, status: "off_shelf" }).then((res) => {
            this.$showToast("下架成功");
            this.list = [];
            this.selectData();
          });
        })
        .catch((err) => {
          this.$showToast("已取消");
        });
    },
    changeTopTabs(name) {
      console.log(this.active);
      console.log(name);

      this.active = name.detail.index;
      if (this.active === 1) {
        this.selectComponent("#activeName").resize();
        this.initForm();
        this.fileList = [];
        this.quickSleced = {};
        this.fileUrlList = [];
      }
    },
    editPeripheral(id) {
      const _this = this;

      getById({ id: id }).then((res) => {
        if (res.data) {
          _this.form = Object.assign({}, _this.form, res.data);
          _this.form.releaseTime = _this.$common.transDate(
            _this.form.releaseTime
          );
          const typeName = _this.dic_SelectList.periphery_type[_this.form.type];
          _this.quickSleced.value = _this.form.type;
          if (_this.form.fileUrl && _this.form.fileUrl.length > 2) {
            _this.fileList = [];
            const fileUrlList = JSON.parse(_this.form.fileUrl);
            fileUrlList.forEach((item) => {
              _this.fileList.push(
                JSON.parse(
                  '{"url":"' +
                    item.url.replace("/server", "/smartParkH5Server") +
                    '","isImage": true}'
                )
              );
            });
            console.log(fileUrlList);
            _this.fileUrlList = fileUrlList;
          }
          _this.active = 0;
        }
      });
    },
    selectData() {
      const _this = this;

      list(_this.params).then((res) => {
        if (res.data) {
          res.data.forEach(function (item) {
            const jsonMap = _this.getItemJson(item);
            _this.list.push(jsonMap);
          });
        }
        console.log(_this.list);
      });
    },
    selectChange(name, title) {
      console.log(name.detail.name);
      console.log(
        "this.tabsList[this.activeName]",
        this.tabsList[this.activeName]
      );
      this.list = [];
      this.params.type = !name.detail.name ? "" : name.detail.name;
      console.log(this.params.type);
      this.selectData();
    },
    getItemJson: function (item) {
      item.releaseTime = this.$common.transDate(item.releaseTime);

      let obj = {};
      for (let i = 0; i < this.dic_SelectList.periphery_type.length; i++) {
        obj[this.dic_SelectList.periphery_type[i].value] =
          this.dic_SelectList.periphery_type[i].label;
      }
      item.type = obj[item.type];

      return item;
    },
    deleteFileList(event) {
      this.fileUrlList.splice(event.detail.index, 1);
    },
    afterRead(event) {
      console.log(event);
      let that = this;
      const { file } = event.detail;
      uni.uploadFile({
        url: that.$constant.BASE_URI + "/wx/fileController/upload2",
        filePath: file.url,
        name: "file",
        formData: { user: "test" },
        success(res) {
          // 上传完成需要更新 fileList
          let data = JSON.parse(res.data);
          that.fileUrlList.push({
            name: JSON.parse(data.data[0]).name,
            size: JSON.parse(data.data[0]).size,
            imgUrl: "/FileController/download/" + data.data[1],
            url:
              that.$constant.BASE_URI +
              "/FileController/download/" +
              data.data[1],
            isImage: true,
          });
        },
        fail(res) {},
      });
    },
    save() {
      let that = this;
      console.log(123123);
      console.log(that.form);
      console.log(that.fileUrlList);
      try {
        that.form.fileUrl = JSON.stringify(that.fileUrlList);
        that.form.type = that.quickSleced.value;
        that.form.releaseTime = that.$common.transServDate(new Date());
        if (this.form.id !== "") {
          edit(this.form).then((res) => {
            that.$showToast("发布成功");
            console.log(res);
            that.active = 1;
            that.initForm();
            that.fileList = [];
            that.quickSleced = {};
            that.fileUrlList = [];
            that.list = [];
            that.selectData();
            // this.$router.push({
            //     path: '/peripheralService-app', query: { active: 1 }
            // })
          });
        } else {
          add(that.form).then((res) => {
            that.$showToast("发布成功");
            that.active = 1;
            that.initForm();
            that.fileList = [];
            that.quickSleced = {};
            that.fileUrlList = [];
            that.list = [];
            that.selectData();
            // this.$router.push({
            //     path: '/peripheralService-app', query: { active: 1 }
            // })
          });
        }
      } catch (error) {
        console.log(error);
      }
    },
    initForm() {
      let form = {
        id: "",
        businessName: "",
        type: "",
        businessAddress: "",
        businessPhone: "",
        fileUrl: "",
        introduction: "",
        source: "2",
        releaseType: "periphery",
        publisherUserId: getUserLocalStorageInfo().user.id,
        status: "published",
      };
      this.form = form;
    },
    quickSelect(item) {
      if (this.quickSleced.value && this.quickSleced.value === item.value) {
        this.quickSleced = {};
      } else {
        this.quickSleced = item;
      }
    },

    beforeDelete(file, detail) {
      // this.handleImagUrlList = []
      const vm = this;
      // name.index代表图片的索引
      vm.fileUrlList.splice(detail.index, 1);
      return (file, name) => {
        const fileIndex = name.index;
        vm.fileUrlList[detail.index].splice(fileIndex, 1);
      };
    },
    /**
     * 上传图片
     */
    uploadImg(file) {
      const _this = this;
      const formParam = new FormData(); // 创建form对象
      formParam.append("file", file.file); // 通过append向form对象添加数据
      console.log(formParam.get("file")); // FormData私有类对象，访问不到，可以通过get判断值是否传进去
      // upload(formParam).then((res) => {
      //     console.log(res)
      // })
      const config = {
        headers: {
          "Content-Type": "multipart/form-data",
          "MVVM-Key": String(new Date().getTime()),
          xx: "anything",
        }, // 这里是重点，需要和后台沟通好请求头，Content-Type不一定是这个值
      }; // 添加请求头
      return new Promise((resolve, reject) => {
        axios
          .post(
            "/smartParkH5Server/wx/fileController/upload",
            formParam,
            config
          )
          .then((response) => {
            debugger;
            let files = response.data.data.substring(
              1,
              response.data.data.length
            );
            files = files.substring(0, files.length - 1);
            _this.fileUrlList.push(_this.$common.castEval(files));
          })
          .catch((err, x) => {
            reject(err, x);
          });
      });
    },
  },
};
</script>
  
  <style lang="scss" type="text/scss" scoped>
.peripheral {
  /deep/.van-tabs__wrap {
    height: 100rpx;
    background: #ffffff;
    box-shadow: 0px 5rpx 10rpx 0px rgba(0, 0, 0, 0.05);
    margin-bottom: 10rpx;
  }
  .tel-num {
    margin: 0 25rpx;
    border-top: 1rpx solid rgba(242, 242, 242, 1);
    border-bottom: 1rpx solid rgba(242, 242, 242, 1);
  }
  .tabs-box {
    margin: 20rpx 0;

    .part-1 {
      background: #fff;
      padding: 40rpx 30rpx 20rpx;
      margin-bottom: 20rpx;
    }
    .page-2 {
      background: #fff;
      .block-cell-item {
        padding-top: 0;
      }
      .custom-textarea-box {
        padding-bottom: 40rpx;
      }
      .address {
        .position-nav {
          border-radius: 10rpx;
        }
      }
    }
    /deep/.van-tab {
      padding: 0 30rpx;
      span {
        display: inline-block;
        text-align: center;
        font-size: 30rpx;
      }
    }
    .tab-tab-box {
      padding: 30rpx 30rpx 0;
      .tab-tab-card {
        background: #ffffff;
        box-shadow: 0px 0px 15rpx 0px rgba(0, 0, 0, 0.1);
        border-radius: 10rpx;
        padding: 40rpx 30rpx 20rpx;
        margin-bottom: 20rpx;
        .card-top {
          @include flex;
          .left {
            width: 500rpx;
            .top {
              width: 500rpx;
              font-size: 32rpx;
              color: #333;
              //   @include line-over;
            }
            .bottom {
              font-size: 28rpx;
              color: #999999;
            }
          }

          .right {
            align-self: flex-start;
            text-align: center;
            span {
              padding: 0 13rpx;
              font-size: 24rpx;
              line-height: 40rpx;
            }
          }
        }
        .card-bottom {
          text-align: right;
          height: 80rpx;
          display: flex;
          justify-content: flex-end;
          align-items: center;
        }
        &:last-child {
          margin-bottom: 0px;
        }
      }
    }
  }
}
</style>
  <style lang="scss">
.custom-select-list {
  color: #666666;
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  li {
    font-size: 22rpx;
    margin-bottom: 25rpx;
    padding: 20rpx 0;
    width: 22%;
    text-align: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    border-radius: 10rpx;
    border: 2rpx solid #cccccc;
    &.active {
      color: #6600ff;
      border-color: #6600ff;
    }
  }
}
.white-box {
  width: 100%;
  font-size: 28px;
  padding: 0 40px;
  background-color: #ffffff;
  box-sizing: border-box;
  &:not(:last-child) {
    margin-bottom: 30px;
  }
  .flex-item {
    align-items: center;
    .tel-box {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      .custom-tel-component {
        margin-left: 20px;
      }
    }
  }
  .cell-item {
    color: var(--Black);
    padding: 30px 0;
    display: flex;
    justify-content: space-between;
    position: relative;
    &::after {
      position: absolute;
      box-sizing: border-box;
      content: " ";
      pointer-events: none;
      right: 0;
      bottom: 0;
      left: 0;
      border-bottom: 1px solid #ebedf0;
      -webkit-transform: scaleY(0.5);
      transform: scaleY(0.5);
    }
    > .label {
      flex: 1;
      width: 30%;
      .tips {
        font-size: 22px;
        color: var(--greyColor);
      }
      &.required {
        position: relative;
        &::after {
          content: "*";
          color: var(--Red);
          position: absolute;
          font-size: 30px;
          top: -15px;
          left: -15px;
        }
      }
    }
    > .tit {
      color: var(--Black);
      flex: 1;
      width: 70%;
      text-align: right;
      .van-radio-group {
        display: flex;
        justify-content: flex-end;
        .van-radio {
          &:not(:first-child) {
            margin-left: 30px;
          }
        }
      }
    }
  }
  .block-cell-item {
    color: var(--Black);
    padding: 30px 0;
    position: relative;
    &::after {
      position: absolute;
      box-sizing: border-box;
      content: " ";
      pointer-events: none;
      right: 16px;
      bottom: 0;
      left: 16px;
      border-bottom: 1px solid #ebedf0;
      -webkit-transform: scaleY(0.5);
      transform: scaleY(0.5);
    }
    .label {
      width: 100%;
      padding-bottom: 30px;
      &.required {
        position: relative;
        &::after {
          content: "*";
          color: var(--Red);
          position: absolute;
          font-size: 30px;
          top: -15px;
          left: -15px;
        }
      }
      .tips {
        font-size: 22px;
        color: var(--greyColor);
      }
    }
    .tit {
      width: 100%;
      color: var(--Black);
      .van-radio-group {
        display: flex;
        justify-content: flex-end;
        .van-radio {
          &:not(:first-child) {
            margin-left: 30px;
          }
        }
      }
      .textarea {
        background-color: #f8f8f8;
        font-size: 30px;
        color: #b7b7b7;
        border-radius: 10px;
        padding: 30px;
        word-break: break-all;
      }
    }
  }
  .custom-white-box-content {
    padding-bottom: 30px;
  }
}
.custom-item-tit {
  height: 100rpx;
  font-size: 32rpx;
  color: #333333;
  padding: 20rpx 0;
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  .tit {
    padding-left: 20rpx;
    position: relative;
    &::after {
      content: "";
      width: 6rpx;
      height: 90%;
      background-color: #976dec;
      position: absolute;
      border-radius: 3rpx;
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }
  .more {
    font-size: 28rpx;
    color: #6600ff;
    display: flex;
    align-items: center;
    i {
      padding-left: 10rpx;
      color: #b5b5b5;
    }
  }
}
.bottom-button {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100rpx;
  font-size: 36rpx;
  color: #ffffff;
  background-color: #60f;
  display: flex;
  align-items: center;
  justify-content: center;
  .btn {
    color: #fff;
    background-color: #6600ff;
    font-size: 34rpx;

    border-radius: 10rpx;
  }
}
.custom-input-box {
  height: 80rpx;
  color: #333333;
  font-size: 30rpx;
  background: #f8f8f8;
  border-radius: 10rpx;

  .txt {
    width: 100%;
    height: 100%;
    text-align: center;
    padding: 0 20rpx;
    line-height: 80rpx;
    box-sizing: border-box;
  }
  input {
    width: 100%;
    height: 100%;
    background: transparent;
    border: transparent;
    padding: 0 20rpx;
    color: #333333;
    box-sizing: border-box;
  }
}
.normal-button-app {
  font-size: 26rpx;
  padding: 13rpx 35rpx;
  border-radius: 30rpx;
  margin-left: 26rpx;
  //  紫色
  &.z-bt {
    border: 1px solid #6600ff;
    background: #ecdfff;
    color: #6600ff;
  }
  // 黄色
  &.y-bt {
    border: 1px solid #ffa913;
    background: #fff7e8;
    color: #ffa913;
  }
  //绿色
  &.l-bt {
    border: 1px solid #54d478;
    background: #9bd8ac4d;
    color: #54d478;
  }
  //红色
  &.r-bt {
    border: 1px solid #f61212;
    background: #ffebeb;
    color: #e80f0f;
  }
  // 灰色
  &.h-bt {
    border: 1px solid #888888;
    background: #fafafa;
    color: #555555;
  }
}
</style>