import { putFeedback } from "../../../api/order.js";
import { getFileNameUUID } from "../../../utils/util";
import { __FAIL_FN } from "../../../utils/network";
const loginUrl = require("../../../api/index.js").config;
const baseUrl = require("../../../api/index.js").config;
const masses = require("../../../api/masses.js");
const ossUse = require("../../../api/dir.js").config;
const ossOrder = require("../../../api/ossOrder.js");

var { Loading, Tips } = getApp();
Page({
  data: {
    disheInfo: {},
    storelist: [],
    evalText: ["待改进", "待改进", "一般", "满意", "超赞"],
    rider: [
      {
        label: "骑手",
        num: 5,
        filid: "deliveryScore",
      },
    ],
    eval: [
      {
        label: "口味",
        num: 5,
        filid: "tasteScore",
      },
      {
        label: "包装",
        num: 5,
        filid: "packageScore",
      },
    ],
    checkslist: [
      {
        name: "匿名提交",
        value: "0",
        checked: true,
      },
    ],
    detailValue: [],
    orderid: "",
    foodlist: [],
    evalInput: "",
    uploadImg: [],
    newList: [],
    upCount: 0,
    aliOss: {},
  },
  onLoad() {
    var that = this;
    that.getCommentlist();
    try {
      const info = wx.getStorageSync("j_feedback");
      this.setData({
        disheInfo: info,
        orderid: info.orderId,
      });
    } catch (e) {
      wx.navigateBack({
        delta: 1,
      });
    }
  },
  onShow() {
    var that = this;
    that.takeGood();
  },
  chooseDelivery(e) {
    let data = e.currentTarget.dataset;
    const { type, num } = data;
    // let change = `eval[${type}].num`
    console.log(type, num);
    this.setData({
      [`rider[${type}].num`]: num + 1,
    });
  },
  chooseStar(e) {
    let data = e.currentTarget.dataset;
    const { type, num } = data;
    // let change = `eval[${type}].num`
    console.log(type, num);
    this.setData({
      [`eval[${type}].num`]: num + 1,
    });
  },
  getEvalData(e) {
    let value = e.detail.value;
    this.setData({
      evalInput: value,
    });
  },
  chooseImage() {
    const that = this;
    wx.chooseImage({
      count: 3,
      sizeType: ["compressed"],
      sourceType: ["album", "camera"],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        that.setData({
          uploadImg: tempFilePaths,
        });
      },
      fail(err) {
        const { errMsg } = err;

        wx.showToast({
          title: /cancel/.test(errMsg)
            ? `取消选择图片`
            : "选择图片出错，请重试",
          icon: "none",
        });
      },
    });
  },
  delImage(e) {
    const { index } = e.currentTarget.dataset;
    let list = this.data.uploadImg;
    list.splice(index, 1);
    this.setData({
      uploadImg: list,
    });
  },
  submitideaInfo() {
    let send = {};
    var that = this;
    var test = [];
    const orderId = this.data.disheInfo.orderId;
    try {
      const memberId = wx.getStorageSync("memberId");
      send.content = this.data.evalInput;
      send.deliveryScore = that.data.rider[0].num;
      send.tasteScore = that.data.eval[0].num;
      send.packageScore = that.data.eval[1].num;
      send.deliveryComment = that.data.detailValue;
      send.anonymousFlag = that.data.checkflag;
      that.data.foodlist.forEach((ele, index) => {
        if (ele.upDown) {
          test.push({
            foodName: ele.name,
            id: ele.id,
            upDown: ele.upDown,
          });
        } else {
        }
      });
      send.foodUpDownList = test;
      putFeedback(
        `${baseUrl.waimaiUrl}/client/${memberId}/order-feedback/${orderId}`,
        {},
        send,
        "加载中",
        function (res) {
          wx.showToast({
            title: res.message || "评价成功",
            icon: "none",
          });
          setTimeout(() => {
            try {
              wx.setStorageSync("j_refresh", true);
            } catch (e) {
              console.error(e);
            }
            wx.navigateBack({
              delta: 1,
            });
          }, 1300);
        },
        (err) => {
          wx.showToast({
            title: err.message,
            icon: "none",
          });
        }
      );
    } catch (e) {
      wx.showToast({
        title: "请重试",
        icon: "none",
      });
      console.log(e);
    }
  },
  submitInfo(imgs) {
    let send = {};
    var that = this;
    const orderId = this.data.disheInfo.orderId;
    try {
      const memberId = wx.getStorageSync("memberId");
      var test = [];
      send.content = this.data.evalInput;
      send.images = imgs;
      send.deliveryScore = that.data.rider[0].num;
      send.tasteScore = that.data.eval[0].num;
      send.packageScore = that.data.eval[1].num;
      send.deliveryComment = that.data.detailValue;
      send.anonymousFlag = that.data.checkflag;
      that.data.foodlist.forEach((ele, index) => {
        if (ele.upDown) {
          test.push({
            foodName: ele.name,
            id: ele.id,
            upDown: ele.upDown,
          });
        } else {
        }
      });
      send.foodUpDownList = test;
      putFeedback(
        `${baseUrl.waimaiUrl}/client/${memberId}/order-feedback/${orderId}`,
        {},
        send,
        "加载中",
        function (res) {
          wx.showToast({
            title: res.message || "评价成功",
            icon: "none",
          });
          setTimeout(() => {
            try {
              wx.setStorageSync("j_refresh", true);
            } catch (e) {
              console.error(e);
            }
            wx.navigateBack({
              delta: 1,
            });
          }, 700);
        },
        (err) => {
          wx.showToast({
            title: err.message,
            icon: "none",
          });
        }
      );
    } catch (e) {
      wx.showToast({
        title: "请重试",
        icon: "none",
      });
    }
  },
  // 提交反馈
  uploadImage() {
    var that = this;
    const { uploadImg: list, evalInput, upCount, foodlist } = this.data;
    let flag = false;
    let ideaflag = false;

    for (let i = 0; i < foodlist.length; i++) {
      const ele = foodlist[i];
      if (!ele.upDown) {
        wx.showToast({
          title: `请对 [${ele.name}] 进行评价`,
          icon: "none",
          duration: 2000,
        });
        flag = true;
        ideaflag = false;
        break;
      }
    }
    if (list.length > 0) {
      ideaflag = true;
    }
    if (flag) return;
    Loading("反馈上传中");
    if (ideaflag) {
      var url = list[upCount];
      ossOrder.takeSign(
        loginUrl.ossUrl + "/aliyun-oss/TOP50/sign",
        {
          dir: ossUse.useDir,
        },
        {},
        "加载中",
        function (res) {
          that.setData({
            aliOss: res.results,
          });
          that.stepUpload(url);
        },
        function (err) {
          console.log("debug 获取OSS签名错误，ERR", err);
          __FAIL_FN({ res: err });
        }
      );
    } else {
      that.submitideaInfo();
    }
  },
  stepUpload(url) {
    // const fileName = "fb_" + getFileNameUUID();
    const fileName = "miniapp/feedback" + "/fb_" + getFileNameUUID();
    const { aliOss } = this.data;
    console.log("ali配置", aliOss);
    const self = this;
    wx.uploadFile({
      url: aliOss.host,
      filePath: url,
      name: "file",
      fileName: fileName,
      formData: {
        name: url,
        key: aliOss.dir + fileName,
        OSSAccessKeyId: aliOss.accessid,
        success_action_status: "200",
        policy: aliOss.policy || self.data.aliOss.policy,
        signature: aliOss.signature || self.data.aliOss.signature,
      },
      success: function (res) {
        if (res.statusCode >= 400) {
          Tips("上传图片出错，请重试");
          console.log(res);
          return;
        }
        const { upCount } = self.data;
        const filid = `newList[${upCount}]`;
        self.setData(
          {
            upCount: ++self.data.upCount,
            [filid]: `${aliOss.host}/${aliOss.dir}${fileName}`,
            // [filid]: `${fileName}`
          },
          () => {
            const { uploadImg: list, upCount } = self.data;
            if (upCount === list.length) {
              const { newList } = self.data;
              self.submitInfo(newList);
              // self.submitInfo(fileName);
              return;
            }
            self.stepUpload(list[upCount]);
          }
        );
      },
      fail: function (res) {
        console.log("debug 图片上传，ERR", res);
        wx.showToast({
          title: "图片上传失败",
          icon: "none",
        });
      },
    });
  },
  // 菜品列表
  takeGood: function () {
    var that = this;
    let memberid = wx.getStorageSync("memberId");
    masses.takeFeebackfood(
      baseUrl.waimaiUrl +
        "/client/" +
        memberid +
        "/order-feedback/" +
        that.data.orderid +
        "/foods",
      {},
      {},
      "加载中",
      function (res) {
        var result = res.results;
        for (var i = 0; i < result.commentFoodList.length; i++) {
          result.commentFoodList[i].zanflag = false;
          result.commentFoodList[i].caiflag = false;
        }
        that.setData({
          foodlist: result.commentFoodList,
          storelist: result,
        });
      },
      function (err) {
        console.log("debug 获取反馈菜品错误 ERR", err);
        __FAIL_FN({ res: err });
      }
    );
  },
  takeZan: function (e) {
    var that = this;
    let index = e.currentTarget.dataset.index;
    that.data.foodlist[index].zanflag = true;
    that.data.foodlist[index].caiflag = false;
    that.data.foodlist[index].upDown = 1;
    that.setData({
      foodlist: that.data.foodlist,
    });
  },
  takeCai: function (e) {
    var that = this;
    let index = e.currentTarget.dataset.index;
    that.data.foodlist[index].zanflag = false;
    that.data.foodlist[index].caiflag = true;
    that.data.foodlist[index].upDown = 2;
    that.setData({
      foodlist: that.data.foodlist,
    });
  },
  // 骑手评价
  checkedBtn: function (e) {
    var that = this;
    let string = "obtnArry[" + e.target.dataset.index + "].selected";
    // const checkedicon = "obtnArry[" + e.target.dataset.index + "].selected";
    console.log(!that.data.obtnArry[e.target.dataset.index].selected);
    that.setData({
      [string]: !that.data.obtnArry[e.target.dataset.index].selected,
    });
    let detailValue = that.data.obtnArry
      .filter((it) => it.selected)
      .map((it) => it.name);
    console.log("所有选中的值为：", detailValue);
    that.setData({
      detailValue: detailValue,
    });
  },
  // 匿名提交
  checkboxChange(e) {
    var that = this;
    console.log("checkbox发生change事件，携带value值为：", e.detail.value);
    if (e.detail.value == "0") {
      that.setData({
        checkflag: true,
      });
    } else {
      that.setData({
        checkflag: false,
      });
    }
  },
  // 骑手评语列表
  getCommentlist: function () {
    var that = this;
    masses.getCommentlist(
      baseUrl.merchantUrl + "/delivery_comment/list",
      {},
      {},
      "加载中",
      function (res) {
        var result = res.results;
        that.setData({
          obtnArry: result,
        });
      },
      function (err) {
        console.log("debug 获取骑手评语错误 ERR", err);
        __FAIL_FN({ res: err });
      }
    );
  },
});
