import HeaderData from "../../components/HeaderData";
import HistogramHorizontal from "../../components/HistogramHorizontal";
import HistogramHorizontals from "../../components/HistogramHorizontals";
import api from '../../api/test'
import editorApi from '../../api/editor'
import timeFormat from '../../util/time'
import { format } from "util";
export default {
  components: {
    HeaderData, HistogramHorizontal, HistogramHorizontals
  },
  data() {
    return {
      isCopy: false,
      houseList: [],
      ownHouseName: "所属项目",
      dataList: [],
      isFilter: false,
      isShowTable: true,
      checkList: [[]],
      data: [],
      value: [],
      oldValue: [],
      options: [],
      questionList: [],
      questionListSel: [],
      filterList: [""],
      questionChilds: [],
      answerData: [],
      currentDate: null,
      filterStr: "",
      chartData: [],
      isCrossAnalyse: false,
      condition: [],
      analyseCommandSel: "全部",
      analyseOptions: [],
      analyseValue: [],
      crossAnalyse: [],
      optionsX: [],
      optionsXValue: [],
      optionsXOldValue: [],
      optionsY: [],
      optionsYValue: [],
      optionsYOldValue: [],

      filterXList: [""],
      filterYList: [""],
      selectedDataList: [],
    }
  },
  watch: {
    answerData: function (val) {
      var questionList = val.questionList;
      this.chartData = []
      for (var i = 0; i < questionList.length; i++) {
        var question = questionList[i];
        var data = []
        var optionList = question.optionList;
        for (var j = 0; j < optionList.length; j++) {
          data.push({ genre: optionList[j].content, sold: optionList[j].answerCount })
        }
        var conditionQuestion = { data: data, ...question }
        this.chartData.push(conditionQuestion);
      }
    },
    analyseCommandSel: function (val) {
      this.analyseOptions = [];
      this.analyseValue = [];
      if (val == "全部") {

      } else if (val == "数据包") {
        var bagList = this.condition.bagList;
        for (var i = 0; i < bagList.length; i++) {
          this.analyseOptions.push({ value: bagList[i].analyseBagId, label: bagList[i].title, disabled: false })
        }
      } else {
        var locationList = this.condition.locationList;
        let locationTemp = []
        for (var i = 0; i < locationList.length; i++) {
          var item = locationList[i]
          if (item.city == "") {
            item.city = item.province;
          }
          locationTemp.push(item)
        }
        locationList = locationTemp;
        let result = Object.values(locationList.reduce((m, n) => {
          if (!m[n.province]) {
            m[n.province] = { value: n.province, children: [] }
          }
          m[n.province].children.push(n)
          return m
        }, {}))
        console.log("XXXX:result:", result)
        var arr = []
        for (var i = 0; i < result.length; i++) {

          var list = result[i].children;
          let results = Object.values(list.reduce((m, n) => {
            if (!m[n.city]) {
              m[n.city] = { value: n.city, label: n.city, children: [] }
            }
            m[n.city].children.push({ value: n.district, label: n.district })
            return m
          }, {}))
          arr.push({ value: result[i].value, label: result[i].value, children: results })
        }

        this.analyseOptions = arr;
      }
    }
  },
  created() {
    this.houseList = [];
    editorApi.houseList().then((res) => {
      if (res.success) {
        this.houseList = res.list;
      }
    });
    this.getTestList();
  },
  methods: {
    async changeTest(item) {
      console.log("XXXXXX1", item);
      var list = []
      for (var i = 0; i < this.dataList.length; i++) {
        var element = this.dataList[i]
        if (item._id == element._id) {
          element.isSelected = !element.isSelected;
        }
        list.push(element)
      }
      console.log("XXXxXXX", list);
      this.dataList = list;

      this.options = []
      this.questionList = []
      for (var i = 0; i < this.dataList.length; i++) {
        var element = this.dataList[i]
        if (element.isSelected) {
          this.getCNCTestDetail(element)
        }
      }

      this.optionsX = []
      for (var i = 0; i < this.dataList.length; i++) {
        var element = this.dataList[i]
        if (element.isSelected) {
          this.getCNCTestDetailX(element)
        }
      }

      this.optionsY = []
      for (var i = 0; i < this.dataList.length; i++) {
        var element = this.dataList[i]
        if (element.isSelected) {
          this.getCNCTestDetailY(element)
        }
      }
    },
    async getCondition() {
      var testThemesIdList = [];
      for (var i = 0; i < this.options.length; i++) {
        var element = this.options[i]
        testThemesIdList.push(element.id);
      }
      let data = {
        testThemesIdList: testThemesIdList
      }
      api.condition(data).then((res) => {
        if (res.success) {
          console.log("success", res.single);
          this.condition = res.single;
        } else {
          console.log("error");
        }
      });
    },
    async getCNCTestDetail(item) {
      this.currentDate = timeFormat.getNowFormatDate();
      let data = {
        testThemesIdList: [item._id]
      }
      api.answerData(data).then((res) => {
        if (res.success) {
          this.answerData = res.single;
          console.log("success", res);
          var questionList = res.single.questionList;
          var children = []
          for (var i = 0; i < questionList.length; i++) {
            children.push({ value: questionList[i].questionId, label: questionList[i].content, disabled: false })
          }
          var element = { value: item._id, label: item.title, children: children, id: item._id };
          this.options.push(element);
          this.questionList = questionList;
          // 查询数据包列表
          this.getCondition();
        } else {
          console.log("error");
        }
      });
    },
    async getCNCTestDetailX(item) {
      let data = {
        testThemesIdList: [item._id]
      }
      api.answerData(data).then((res) => {
        if (res.success) {
          this.answerData = res.single;
          console.log("success", res);
          var questionList = res.single.questionList;
          var children = []
          for (var i = 0; i < questionList.length; i++) {
            children.push({ value: questionList[i].questionId, label: questionList[i].content, disabled: false })
          }
          var element = { value: item._id, label: item.title, children: children, id: item._id };
          this.optionsX.push(element);
        } else {
          console.log("error");
        }
      });
    },
    async getCNCTestDetailY(item) {
      let data = {
        testThemesIdList: [item._id]
      }
      api.answerData(data).then((res) => {
        if (res.success) {
          this.answerData = res.single;
          console.log("success", res);
          var questionList = res.single.questionList;
          var children = []
          for (var i = 0; i < questionList.length; i++) {
            children.push({ value: questionList[i].questionId, label: questionList[i].content, disabled: false })
          }
          var element = { value: item._id, label: item.title, children: children, id: item._id };
          this.optionsY.push(element);
        } else {
          console.log("error");
        }
      });
    },
    handleChange(value, index) {
      console.log(value, index, this.oldValue);
      for (var i = 0; i < this.questionList.length; i++) {
        if (value[1] == this.questionList[i].questionId) {
          if (this.oldValue.length >= index + 1) {
            console.log("XXXXXXXXXXXXX");
            this.setOptionsDisabled(this.oldValue[index], false);
          }
          this.questionListSel[index] = this.questionList[i];
        }
      }
      this.setOptionsDisabled(value, true);

      this.value[index] = value;
      this.oldValue[index] = value;
      this.checkList.splice(index, 1, []);
      this.questionChilds.splice(index, 1, []);
    },
    handleChangeX(value, index) {
      console.log("handleChangeX", value, index, this.optionsXOldValue);
      for (var i = 0; i < this.questionList.length; i++) {
        if (value[1] == this.questionList[i].questionId) {
          if (this.optionsXOldValue.length >= index + 1) {
            console.log("XXXXXXXXXXXXX");
            this.setOptionsDisabledXY(this.optionsXOldValue[index], false, 0);

            this.setOptionsDisabledXY(this.optionsYOldValue[index], false, 1);
          }
          // this.questionListSel[index] = this.questionList[i];
        }
      }

      this.setOptionsDisabledXY(value, true, 1);
      this.setOptionsDisabledXY(value, true, 0);

      this.optionsXValue[index] = value;
      this.optionsXOldValue[index] = value;
      // this.checkList.splice(index, 1, []);
      // this.questionChilds.splice(index, 1, []);
    },
    handleChangeY(value, index) {
      console.log("handleChangeX", value, index, this.optionsYOldValue);
      for (var i = 0; i < this.questionList.length; i++) {
        if (value[1] == this.questionList[i].questionId) {
          if (this.optionsYOldValue.length >= index + 1) {
            console.log("XXXXXXXXXXXXX");
            this.setOptionsDisabledXY(this.optionsYOldValue[index], false, 1);
            this.setOptionsDisabledXY(this.optionsYOldValue[index], false, 0);
          }
          // this.questionListSel[index] = this.questionList[i];
        }
      }
      this.setOptionsDisabledXY(value, true, 1);
      this.setOptionsDisabledXY(value, true, 0);

      this.optionsYValue[index] = value;
      this.optionsYOldValue[index] = value;
      // this.checkList.splice(index, 1, []);
      // this.questionChilds.splice(index, 1, []);
    },
    addfilterX() {
      this.filterXList.push('');
    },
    addfilterY() {
      this.filterYList.push('');
    },
    handleAnalyseChange(value) {
      console.log(value);
    },
    setOptionsDisabledXY(value, disabled, type = 0) {
      var newOptions = [];
      console.log("XXXXXXX", value)
      var options = type == 0 ? this.optionsX : this.optionsY;
      for (var i = 0; i < options.length; i++) {
        var item = options[i];
        if (item.value == value[0]) {
          for (var j = 0; j < options[i].children.length; j++) {
            var children = []
            var element = options[i].children[j];
            if (element.value == value[1]) {
              element.disabled = disabled
            }
            children.push(element)
          }
        }
        newOptions.push(item)
      }
      if (type == 0) {
        this.optionsX = newOptions;
      } else {
        this.optionsY = newOptions;
      }

    },
    setOptionsDisabled(value, disabled) {
      var newOptions = [];
      console.log("XXXXXXX", value)
      for (var i = 0; i < this.options.length; i++) {
        var item = this.options[i];
        if (item.value == value[0]) {
          for (var j = 0; j < this.options[i].children.length; j++) {
            var children = []
            var element = this.options[i].children[j];
            if (element.value == value[1]) {
              element.disabled = disabled
            }
            children.push(element)
          }
        }
        newOptions.push(item)
      }
      this.options = newOptions;
    },
    addFilter() {
      this.filterList.push('');
      this.checkList.push([]);
    },
    delFilter(index) {
      if (this.value[index]) {
        this.setOptionsDisabled(this.value[index], false);
      }

      this.filterList.splice(index, 1);
      this.value.splice(index, 1);

      this.questionListSel.splice(index, 1);
      this.questionChilds.splice(index, 1);
      this.checkList.splice(index, 1);
    },
    projectCommand(command) {
      if (this.houseList.indexOf(command) == -1) {
        console.log("不存在");
        this.ownHouseName = "所属项目";
      } else {
        console.log("存在", command.houseName);
        this.ownHouseName = command.houseName;
      }
      this.getTestList();
    },
    analyseCommand(command) {
      console.log("XXXXXXX", command)
      if (command == -1) {
        this.analyseCommandSel = "全部";
      } else if (command == 0) {
        this.analyseCommandSel = "数据包";
      } else {
        this.analyseCommandSel = "区域";
      }
      // this.getTestList();
    },
    changequestionChild(checked, value, index) {
      console.log("XXXXXX", value, index, checked);

      var arr = this.questionChilds;
      if (this.questionChilds.length <= index) { // 没有
        if (checked) {
          console.log("选中");
          for (var i = 0; i < this.filterList.length; i++) {
            if (i < index) {
              if (this.questionChilds.length < index) {
                this.questionChilds.push([]);
              }
            }
          }
          this.questionChilds.push([value]);
        } else {
          console.log("取消选中")
        }
      } else { // 有
        console.log("有")
        var questionList = this.questionChilds[index];
        if (checked) {
          questionList.push(value)
        } else {
          var arr = questionList;
          for (var i = 0; i < questionList.length; i++) {
            var option = questionList[i];
            if (option.optionId == value.optionId) {
              arr.splice(i, 1);
            }
          }
          questionList = arr;
        }
        this.questionChilds[index] = questionList;
      }

    },
    getTestList() {

      let data = {
        "orderType": "",
        "ownHouseName": this.ownHouseName == "所属项目" ? '' : this.ownHouseName,
        "pageNo": 1,
        "pageSize": 100,
        "houseAnswerStatus": ""
      }
      api.testList(data).then((res) => {
        if (res.success) {
          this.total = res.pageModel.total;
          this.dataList = [];
          this.dataList.push(...res.pageModel.resultSet);
          this.dataList.forEach(element => {
            element.isSelected = false
          });
          console.log("success", this.dataList, res.pageModel);
        } else {
          console.log("error");
        }
      });
    },
    async getAnswerData() {
      this.filterStr = "";

      var conditionQuestionList = [];
      var testThemesIdList = [];
      for (var i = 0; i < this.questionChilds.length; i++) {
        var question = this.questionChilds[i];
        var value = this.value[i];
        var optionList = [];
        for (var j = 0; j < question.length; j++) {
          optionList.push({ optionId: question[j].optionId })
          this.filterStr += question[j].content + "/";
        }
        var conditionQuestion = { questionId: value[1], optionList: optionList }
        conditionQuestionList.push(conditionQuestion);
      }

      for (var i = 0; i < this.options.length; i++) {
        testThemesIdList.push(this.options[i].id);
      }
      this.filterStr = this.filterStr.substr(0, this.filterStr.length - 1)
      let data = {
        conditionQuestionList: conditionQuestionList,
        testThemesIdList: testThemesIdList
      }
      api.answerData(data).then((res) => {
        if (res.success) {
          this.answerData = res.single;
          console.log("success", res);
        } else {
          console.log("error");
        }
      });
    },
    saveOnLine() {
      var checkList = [];

      for (var i = 0; i < this.questionChilds.length; i++) {
        var question = this.questionChilds[i]
        for (var j = 0; j < question.length; j++) {
          var option = question[j];
          var questionObj = this.questionListSel[i];
          console.log("SSSSSS", option, questionObj);
          checkList.push({ subOptionContent: option.content, subOptionId: option.optionId, subQuestionContent: questionObj.content, subQuestionId: questionObj.questionId })
        }
      }

      console.log("编辑数据包", checkList);
      this.$prompt("请数据包名称", "提保存筛选条件作为数据包", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
        inputErrorMessage: "数据包名称不为空",
        inputValue: this.title
      })
        .then(({ value }) => {
          let param = {
            checkList: checkList,
            analyseBagTitle: value,
            operator: "admin"
          };
          api.saveAnalyseBag(param).then(res => {
            if (res.success) {
              this.$message.success("保存成功");
            } else {
              this.$message.error("数据加载失败,请重试");
            }
          });
        })
        .catch(() => { });
    },
    async getCrossAnalyse() {

      var analyseBagIdList = [];
      var province = ""
      var city = ""
      var district = ""

      if (this.analyseCommandSel == "数据包") {
        if (this.analyseValue.length > 0) {
          analyseBagIdList.push(this.analyseValue[0])
        }
      } else if (this.analyseCommandSel == "区域") {
        if (this.analyseValue.length > 0) {
          province = this.analyseValue[0]
        } else if (this.analyseValue.length > 1) {
          city = this.analyseValue[1]
        } else if (this.analyseValue.length > 2) {
          district = this.analyseValue[2]
        }
      }
      var testThemesIdList = [];
      for (var i = 0; i < this.options.length; i++) {
        testThemesIdList.push(this.options[i].id);
      }
      var xlist = [];
      var ylist = [];
      for (var i = 0; i < this.questionList.length; i++) {
        var item = this.questionList[i];
        for (var m = 0; m < this.optionsXValue.length; m++) {
          var element = this.optionsXValue[m];
          if (item.questionId == element[1]) {
            xlist.push(item);
          }
        }
        for (var n = 0; n < this.optionsYValue.length; n++) {
          var element = this.optionsYValue[n];
          if (item.questionId == element[1]) {
            ylist.push(item);
          }
        }
      }

      let data = {
        province: province,
        city: city,
        district: district,
        analyseBagIdList: analyseBagIdList,
        testThemesIdList: testThemesIdList,
        xlist: xlist,
        ylist: ylist
      }
      console.log("XXXXXX", data);
      api.crossAnalyse(data).then((res) => {
        if (res.success) {
          console.log("success", res.list);
          var crossAnalyse = res.list;
          this.crossAnalyse = []
          var result = [];
          var rowArr = [];
          for (var n = 0; n < crossAnalyse.length; n++) {
            var arrs = []
            var crossResult = crossAnalyse[n].crossResult;
            console.log("XXXXX", Object.keys(crossResult), Object.values(crossResult))
            rowArr = Object.keys(crossResult);
            var values = Object.values(crossResult)
            for (var m = 0; m < values.length; m++) {
              console.log("SSSSS", Object.keys(values[m]), Object.values(values[m]))
              arrs.push({ name: Object.keys(values[m]), value: Object.values(values[m]) })
            }
            result.push(arrs);
          }

          console.log("AAAAAA", result);

          for (var x = 0; x < result.length; x++) {
            var qqq = result[x];
            var sss = [];
            for (var q = 0; q < qqq.length; q++) {
              sss.push({ name: rowArr[q], title: qqq[q].name, value: qqq[q].value })
            }
            this.crossAnalyse.push({ table: sss, data: [], question: null });
          }
          console.log("SSSSS", this.crossAnalyse);

          for (var x = 0; x < this.crossAnalyse.length; x++) {
            var data = [];
            var top = this.crossAnalyse[x].table;
            for (var y = 0; y < top.length; y++) {
              var one = top[y].value;
              console.log("one", top[y].name)
              for (var z = 0; z < one.length; z++) {
                var two = one[z];
                data.push({ time: top[y].name, type: top[y].title[z], value: two })
              }
            }
            this.crossAnalyse[x].data = data;
          }
          console.log("data", this.crossAnalyse);

        } else {
          console.log("error");
        }
      });
    }


  },
}