<template>
  <div>
    <!--        顶部条-->
    <div class="navBarTOP">
      <van-nav-bar class="navBar" title="填写半月报" left-arrow @click-left="onClickLeft">
        <template #right>
          <span
            v-if="temporaryShow != 'N'"
            @click="tsContentsFn"
            style="
              color: white;
              background: #74a4d9;
              display: block;
              padding: 6px 10px;
              border-radius: 6px;
            "
            >暂存</span
          >
        </template>
      </van-nav-bar>
    </div>
    <!--        主体内容-->
    <div class="container linepAdd">
      <div class="lineGrey"></div>
      <div class="lineGrey"></div>
      <div class="lineGrey"></div>
      <div class="lineGrey"></div>
      <div class="lineGrey"></div>
      <van-collapse v-model="activeNames">
        <template v-if="reportTarget.postType == 'GZ' || reportTarget.BMDType == 'BMD'">
          <!-- 0-历史指标  1-动态指标，String类型 -->
          <template v-if="reportTarget.targetType == '1'">
            <target :homePageIndicatorDate="homePageIndicatorList"></target>
          </template>
          <template v-if="reportTarget.targetType == '0'">
            <Atarget :reportInfo="reportTarget"></Atarget>
            <Btarget :reportInfo="reportTarget"></Btarget>
          </template>
        </template>
        <template v-else>
          <Atarget :reportInfo="reportTarget"></Atarget>
          <Btarget :reportInfo="reportTarget"></Btarget>
        </template>
        <!-- isHistory 是否为历史汇报：0-新汇报 1-历史汇报 -->
        <div class="contentContainer" v-if="reportTarget.isHistory == '0'">
          <reportCustom
            ref="reportCustom"
            :reportCustomData="reportTarget.customTaskList"></reportCustom>
        </div>
        <template v-else>
          <van-collapse-item title="上期工作成果" name="7" class="collapsettitle">
            <template #title>
              <div>上期工作成果 <span class="colorRed">(必填)</span></div>
            </template>
            <div style="margin-top: -10px">
              <div class="weekContent" v-for="(item2, index2) in reportContentsList2" :key="index2">
                <!--              <p class="texttitle"><span class="opint"></span><span>{{ item2.title }}</span><span-->
                <!--                  class="colorRed">(必填)</span></p>-->
                <p class="texttitle texttitle2">计划工作进度</p>
                <p class="contentContainerp1">
                  <van-field
                    v-model="reportContentsList3[index2].doubleWeekContent"
                    rows="4"
                    autosize
                    readonly
                    :formatter="formatter"
                    type="textarea" />
                </p>
                <!--              <p style="min-height: 32px;">{{ reportContentsList3[index2].doubleWeekContent }}</p>-->
                <p class="texttitle texttitle2">实际工作进度</p>
                <p class="contentContainerp">
                  <van-field
                    v-model="item2.doubleWeekContent"
                    rows="4"
                    autosize
                    maxlength="800"
                    :formatter="formatter"
                    type="textarea"
                    show-word-limit />
                </p>
              </div>
            </div>
          </van-collapse-item>
          <van-collapse-item title="本期工作规划" name="8" class="collapsettitle">
            <template #title>
              <div>本期工作规划 <span class="colorRed">(必填)</span></div>
            </template>
            <div style="margin-top: -10px">
              <div class="weekContent" v-for="(item, index) in reportContentsList1" :key="index">
                <p class="contentContainerp">
                  <van-field
                    v-model="item.doubleWeekContent"
                    rows="4"
                    autosize
                    maxlength="800"
                    type="textarea"
                    show-word-limit
                    :formatter="formatter" />
                </p>
              </div>
            </div>
          </van-collapse-item>
        </template>
      </van-collapse>
      <br />
      <br />
      <van-button type="info" size="small" plain class="Btn100" @click="submint"
        >提交半月报</van-button
      >
    </div>
    <br />
    <br />
  </div>
</template>

<script>
import {
  getDetailById,
  double_week_type,
  updateReport,
  getReportInfo,
  tsContents,
} from '@/api/index';
import createStoreBJ from '@/views/componentsTarget/createStoreBJ';
import ZYPlaceOrder from '@/views/componentsTarget/ZYPlaceOrder';
import performanceSAP from '@/views/componentsTarget/performanceSAP';
import ZYSAP from '@/views/componentsTarget/ZYSAP';
import veryGoodPlaceOrder from '@/views/componentsTarget/veryGoodPlaceOrder';
import neiwaiqiangpingtu from '@/views/componentsTarget/neiwaiqiangpingtu';
import zhiganwaiqiangSAP from '@/views/componentsTarget/zhiganwaiqiangSAP';
import Atarget from '@/views/home/Atarget.vue';
import Btarget from '@/views/home/Btarget.vue';
import reportCustom from './reportCustom.vue';
import target from './target.vue';

export default {
  name: 'home',
  components: {
    createStoreBJ,
    ZYPlaceOrder,
    performanceSAP,
    ZYSAP,
    veryGoodPlaceOrder,
    neiwaiqiangpingtu,
    zhiganwaiqiangSAP,
    Atarget,
    Btarget,
    reportCustom,
    target,
  },
  data() {
    return {
      activeNames: [
        '1',
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '11',
        '12',
        '16',
        '17',
        '27',
        '28',
        '29',
      ],
      powerGrade: '',
      value: '2',
      isclick: true,
      reportTargetAll: {},
      reportTarget: {},
      reportContentsList1: [],
      reportContentsList2: [],
      reportContentsList3: [],
      weekType: [],
      temporaryShow: '',
      type: '-1',
      JZQuota: false,
      homePageIndicatorList: null,
    };
  },
  created() {
    this.powerGrade = localStorage.getItem('powerGrade');
    this.temporaryShow = this.$route.query.temporaryShow;
    double_week_type().then((res) => {
      this.weekType = res.data;
    });
    if (this.$route.query.reportId != undefined) {
      this.getDetailById();
    } else {
      this.getReportInfo();
    }
  },
  watch: {
    $route(to, from) {
      this.powerGrade = localStorage.getItem('powerGrade');
      this.getReportInfo();
      this.temporaryShow = this.$route.query.temporaryShow;
      if (to.path == '/doubleWeekly') {
        if (this.$route.query.reportId != undefined) {
          this.getDetailById();
        } else {
          this.getReportInfo();
        }
      }
      // &&from.path=="/home"
      // if(to.path=="/doubleWeekly"&&from.path=="/myHistoricalDaily"){
      //   if(this.$route.query.reportId!=undefined){
      //     this.getDetailById()
      //   }else{
      //     this.getReportInfo()
      //   }
      // }
    },
  },
  methods: {
    formatter(value) {
      return value.replace(
        /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi,
        '',
      );
    },
    getDetailById() {
      let loading1 = this.$toast.loading({
        duration: 0,
        message: '加载中...',
        forbidClick: true,
      });
      getDetailById({ reportId: this.$route.query.reportId }).then((res) => {
        loading1.clear();
        if (res.code == 200) {
          this.JZQuota = false;
          if (res.data.postType == 'JZ') {
            this.JZQuota = true;
          }
          if (res.data.status != '0' && res.data.status != '2') {
            this.$dialog
              .alert({
                title: '系统提示',
                message: '半月报已提交或过期',
              })
              .then(() => {
                window.location.replace(window.location.origin + this.locationOrigin + '/home');
              });
          } else {
            this.homePageIndicatorList = res.data.homePageIndicatorList || null;
            this.reportTargetAll = res.data.reportTargetAll;
            this.reportTarget = res.data;
            this.type = res.data.userType;
            this.reportContents = res.data.reportContents;
            var reportContentsList1 = [];
            var reportContentsList2 = [];
            var reportContentsList3 = [];
            var reportContentsdata = res.data.reportContents;
            for (var i = 0; i < res.data.reportContents.length; i++) {
              reportContentsdata[i].title = this.selectDictLabel(
                this.weekType,
                res.data.reportContents[i].doubleWeekType,
              );
              if (res.data.reportContents[i].type == '2') {
                reportContentsList1.push(reportContentsdata[i]);
              }
              if (res.data.reportContents[i].type == '3') {
                reportContentsList2.push(reportContentsdata[i]);
              }
              if (res.data.reportContents[i].type == '1') {
                reportContentsList3.push(reportContentsdata[i]);
              }
            }
            // var ln1 = reportContentsList1.length
            // var ln2 = reportContentsList3.length
            // if (reportContentsList1.length > reportContentsList3.length) {
            //   var len = ln1 - ln2
            //   for (var x = 0; x < len; x++) {
            //     reportContentsList3.push({
            //       // contentTime: "",
            //       // weekContentAm: "",
            //       doubleWeekContent: "",
            //     })
            //   }
            // }
            if (reportContentsdata.length == 0) {
              // for (var i = 0; i < 6; i++) {
              //   var doubleWeekType = ""
              //   var title = ""
              //   if (i == "0") {
              //     doubleWeekType = "cpm"
              //     title = "产品"
              //
              //   }
              //   if (i == "1") {
              //     doubleWeekType = "qdm"
              //     title = "渠道"
              //   }
              //   if (i == "2") {
              //     doubleWeekType = "yym"
              //     title = "运营"
              //   }
              //   if (i == "3") {
              //     doubleWeekType = "jpm"
              //     title = "竞品"
              //   }
              //   if (i == "4") {
              //     doubleWeekType = "cwm"
              //     title = "财务"
              //   }
              //   if (i == "5") {
              //     doubleWeekType = "rlm"
              //     title = "人力"
              //   }
              reportContentsList1.push({
                title: '',
                doubleWeekContent: '',
                doubleWeekType: '',
                contentTime: this.parseTime(new Date(), '{y}-{m}-{d}'),
                type: 2,
              });
              reportContentsList3.push({
                title: '',
                doubleWeekContent: '',
                doubleWeekType: '',
                contentTime: this.parseTime(new Date(), '{y}-{m}-{d}'),
                type: 1,
              });
              reportContentsList2.push({
                title: '',
                doubleWeekContent: '',
                doubleWeekType: '',
                contentTime: this.parseTime(new Date(), '{y}-{m}-{d}'),
                type: 3,
              });
            } else {
              if (reportContentsList1.length < 1) {
                reportContentsList1.push({
                  title: '',
                  doubleWeekContent: '',
                  doubleWeekType: '',
                  contentTime: this.parseTime(new Date(), '{y}-{m}-{d}'),
                  type: 2,
                });
              }
              if (reportContentsList3.length < 1) {
                reportContentsList3.push({
                  title: '',
                  doubleWeekContent: '',
                  doubleWeekType: '',
                  contentTime: this.parseTime(new Date(), '{y}-{m}-{d}'),
                  type: 1,
                });
              }
              if (reportContentsList2.length < 1) {
                reportContentsList2.push({
                  title: '',
                  doubleWeekContent: '',
                  doubleWeekType: '',
                  contentTime: this.parseTime(new Date(), '{y}-{m}-{d}'),
                  type: 3,
                });
              }
            }
            // }
            this.reportContentsList1 = reportContentsList2; //  1 2   2  3  3  1
            this.reportContentsList2 = reportContentsList1;
            this.reportContentsList3 = reportContentsList3;
          }
        } else {
          this.$toast(res.msg);
        }
      });
    },
    tsContentsFn() {
      if (this.isclick) {
        if (this.reportTarget.isHistory == '1') {
          this.reportTarget.reportContents = [];
          this.reportTarget.reportContents = this.reportContentsList2
            .concat(this.reportContentsList1)
            .concat(this.reportContentsList3);
          this.tsContentsFun(null);
        } else {
          // 新的
          if (this.reportTarget.customTaskList && this.reportTarget.customTaskList.length) {
            // 配置任务
            this.filterReportCustomData((reportCustomAnswers) => {
              this.tsContentsFun(reportCustomAnswers);
            });
          } else {
            // 没有配置任务
            this.tsContentsFun(null);
          }
        }
      }
    },
    tsContentsFun(reportCustomAnswers) {
      let loading1 = this.$toast.loading({
        duration: 0,
        message: '数据提交中...',
        forbidClick: true,
      });
      if (reportCustomAnswers) this.reportTarget.reportCustomAnswers = reportCustomAnswers;
      this.reportTarget.status = '1';
      this.isclick = false;
      tsContents(this.reportTarget).then((res) => {
        loading1.clear();
        this.isclick = true;
        if (res.code == 200) {
          this.$dialog
            .alert({
              title: '系统提示',
              message: '暂存成功',
            })
            .then(() => {
              // if(this.$route.query.reportId!=undefined){
              //   window.location.replace(window.location.origin+"/mobile/myHistoricalDaily")
              // }else{
              //   window.location.replace(window.location.origin+"/mobile/home")
              // }
            });
        } else {
          this.$toast.fail(res.msg);
        }
      });
    },
    reportCustomTabstoreVal(callback) {
      // 必填校验
      this.$refs.reportCustom.$refs.tabstoreVal
        .validate()
        .then(() => {
          // 验证通过
          this.filterReportCustomData(callback);
        })
        .catch((errors) => {
          this.toastLoading().clear();
          return;
        });
    },
    filterReportCustomData(callback) {
      let reportCustomData = this.$refs.reportCustom ? this.$refs.reportCustom.fromData : {} || {};
      let reportCustomAnswers = [];
      for (let i = 0; i < reportCustomData.length; i++) {
        let customData = reportCustomData[i].sfaReportCustomCollections
          ? reportCustomData[i].sfaReportCustomCollections
          : [];
        for (let x = 0; x < customData.length; x++) {
          if (
            customData[x].reportCustomCollectionType == 'dx' ||
            customData[x].reportCustomCollectionType == 'duox'
          ) {
            let optionData = customData[x].sfaReportCustomOptions;
            for (let y = 0; y < optionData.length; y++) {
              if (optionData[y].answerValue == 'Y') {
                reportCustomAnswers.push({
                  reportCustomTaskId: customData[x].reportCustomTaskId,
                  reportCustomCollectionId: optionData[y].reportCustomCollectionId,
                  reportCustomOptionId: optionData[y].reportCustomOptionId,
                  answerValue: 'Y',
                });
              }
            }
          } else {
            if (customData[x].answerValue)
              reportCustomAnswers.push({
                reportCustomTaskId: customData[x].reportCustomTaskId,
                reportCustomCollectionId: customData[x].reportCustomCollectionId,
                answerValue: customData[x].answerValue,
              });
          }
        }
      }
      console.log(reportCustomAnswers);
      callback && callback(reportCustomAnswers);
    },
    // 提交日报
    submint() {
      if (this.isclick) {
        // 旧的
        if (this.reportTarget.isHistory == '1') {
          this.reportTarget.reportContents = [];
          for (var x = 0; x < this.reportContentsList2.length; x++) {
            if (this.reportContentsList2[x].doubleWeekContent.trim() == '') {
              this.$toast('请完善上期半月报内容！');
              return false;
            }
          }
          for (var j = 0; j < this.reportContentsList1.length; j++) {
            if (this.reportContentsList1[j].doubleWeekContent.trim() == '') {
              this.$toast('请完善本期半月报内容！');
              return false;
            }
          }
          if (this.reportContentsList2[0].doubleWeekContent.length > 800) {
            this.$toast('上期半月报内容超过800字！');
            return false;
          }
          if (this.reportContentsList1[0].doubleWeekContent.length > 800) {
            this.$toast('本期半月报内容超过800字！');
            return false;
          }
          this.reportTarget.reportContents = this.reportContentsList2
            .concat(this.reportContentsList1)
            .concat(this.reportContentsList3);
          this.submintFun();
        } else {
          // 新的
          if (this.reportTarget.customTaskList && this.reportTarget.customTaskList.length) {
            // 配置任务
            this.reportCustomTabstoreVal((reportCustomAnswers) => {
              this.submintFun(reportCustomAnswers);
            });
          } else {
            // 没有配置任务
            this.submintFun(null);
          }
        }
      }
    },
    submintFun(reportCustomAnswers) {
      let loading1 = this.$toast.loading({
        duration: 0,
        message: '数据提交中...',
        forbidClick: true,
      });
      if (reportCustomAnswers) this.reportTarget.reportCustomAnswers = reportCustomAnswers;
      this.reportTarget.status = '1';
      this.isclick = false;
      updateReport(this.reportTarget).then((res) => {
        loading1.clear();
        this.isclick = true;
        if (res.code == 200) {
          this.$dialog
            .alert({
              title: '系统提示',
              message: '提交成功',
            })
            .then(() => {
              if (this.$route.query.reportId != undefined) {
                window.location.replace(
                  window.location.origin + this.locationOrigin + '/myHistoricalDaily',
                );
              } else {
                this.onClickLeft();
                // window.location.replace(window.location.origin + '/mobile/home');
              }
            });
        } else {
          this.$toast.fail(res.msg);
        }
      });
    },
    getReportInfo() {
      let loading1 = this.$toast.loading({
        duration: 0,
        message: '加载中...',
        forbidClick: true,
      });
      getReportInfo({ isContent: true }).then((res) => {
        loading1.clear();
        localStorage.setItem('powerGrade', res.data.positionId);
        localStorage.setItem('userDeptLevel', res.data.userDeptLevel);
        this.powerGrade = res.data.positionId;
        this.showButton = res.data.showButton;
        this.reportTargetAll = res.data.reportTargetAll;
        this.reportTarget = res.data;
        this.type = res.data.userType;
        this.homePageIndicatorList = res.data.homePageIndicatorList || null;
        var reportContentsList1 = [];
        var reportContentsList2 = [];
        var reportContentsList3 = [];
        if (res.data.reportContents.length == '0') {
          // for (var i = 0; i < 6; i++) {
          //   var doubleWeekType = ""
          //   var title = ""
          //   if (i == "0") {
          //     doubleWeekType = "cpm"
          //     title = "产品"
          //   }
          //   if (i == "1") {
          //     doubleWeekType = "qdm"
          //     title = "渠道"
          //   }
          //   if (i == "2") {
          //     doubleWeekType = "yym"
          //     title = "运营"
          //   }
          //   if (i == "3") {
          //     doubleWeekType = "jpm"
          //     title = "竞品"
          //   }
          //   if (i == "4") {
          //     doubleWeekType = "cwm"
          //     title = "财务"
          //   }
          //   if (i == "5") {
          //     doubleWeekType = "rlm"
          //     title = "人力"
          //   }
          reportContentsList1.push({
            title: '',
            doubleWeekContent: '',
            doubleWeekType: '',
            contentTime: this.parseTime(new Date(), '{y}-{m}-{d}'),
            type: 3,
          });
          reportContentsList3.push({
            title: '',
            doubleWeekContent: '',
            doubleWeekType: '',
            contentTime: this.parseTime(new Date(), '{y}-{m}-{d}'),
            type: 1,
          });
          reportContentsList2.push({
            title: '',
            doubleWeekContent: '',
            doubleWeekType: '',
            contentTime: this.parseTime(new Date(), '{y}-{m}-{d}'),
            type: 2,
          });
          // }
          this.reportContentsList2 = reportContentsList2;
          this.reportContentsList1 = reportContentsList1;
          this.reportContentsList3 = reportContentsList3;
        } else {
          var reportContentsdata = res.data.reportContents;
          for (var i = 0; i < res.data.reportContents.length; i++) {
            // reportContentsdata[i].title = this.selectDictLabel(this.weekType, res.data.reportContents[i].doubleWeekType)
            if (res.data.reportContents[i].type == '2') {
              reportContentsList2.push(reportContentsdata[i]);
            }
            if (res.data.reportContents[i].type == '3') {
              reportContentsList1.push(reportContentsdata[i]);
            }
            if (res.data.reportContents[i].type == '1') {
              reportContentsList3.push(reportContentsdata[i]);
            }
          }
          if (reportContentsList2.length > 0) {
            this.reportContentsList2 = reportContentsList2;
          } else {
            reportContentsList2.push({
              title: '',
              doubleWeekContent: '',
              doubleWeekType: '',
              contentTime: this.parseTime(new Date(), '{y}-{m}-{d}'),
              type: 2,
            });
            this.reportContentsList2 = reportContentsList2;
          }
          if (reportContentsList1.length > 0) {
            this.reportContentsList1 = reportContentsList1;
          } else {
            reportContentsList1.push({
              title: '',
              doubleWeekContent: '',
              doubleWeekType: '',
              contentTime: this.parseTime(new Date(), '{y}-{m}-{d}'),
              type: 3,
            });
            this.reportContentsList1 = reportContentsList1;
          }
          if (reportContentsList3.length > 0) {
            this.reportContentsList3 = reportContentsList3;
          } else {
            reportContentsList3.push({
              title: '',
              doubleWeekContent: '',
              doubleWeekType: '',
              contentTime: this.parseTime(new Date(), '{y}-{m}-{d}'),
              type: 1,
            });
            this.reportContentsList3 = reportContentsList3;
          }
        }
      });
    },
    onClickLeft() {
      this.$router.go(-1);
    },
  },
};
</script>
<style scoped>
.container {
  margin: 10px;
}

.container .van-collapse-item {
  margin-bottom: 10px;
  border-radius: 6px;
  overflow: hidden;
}

.linepAdd p {
  margin: 10px 0 0 0;
  font-size: 14px;
  color: #666;
}

.linepAdd .weekContent {
  padding-top: 5px;
}

.linepAdd .weekContent p {
  padding: 5px 0;
  margin: 0;
  padding-left: 10px;
}

.linepAdd .weekContent .texttitle {
  color: #0057ba;
  position: relative;
  padding-left: 10px;
}

.linepAdd .weekContent .texttitle .opint {
  position: absolute;
  left: 0px;
  top: 10px;
  margin-right: 6px;
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 10px;
  background-color: #004d8c;
}

.leftTitle {
  background-color: #74a4d9;
  color: #fff;
  display: inline-block;
  padding: 0 4px;
  border-radius: 2px;
}

.rightTitle {
  background-color: #e7b4bb;
  color: #fff;
  display: inline-block;
  padding: 0 4px;
  border-radius: 2px;
}
</style>
<style>
.linepAdd .van-cell__title {
  color: #1e5398;
  font-weight: 500;
  font-size: 16px;
}

.Btn100 {
  display: block;
  width: 100%;
  border-radius: 6px;
  color: #fff !important;
  background-color: #0057ba;
  border: 1px solid #0057ba;
  height: 44px;
}

.linepAdd .contentContainer {
  background-color: white;
  border-radius: 8px;
  padding: 10px 16px;
  margin-bottom: 10px;
}

.linepAdd .contentContainer .contentContainerTitle {
  color: #222;
}

.linepAdd .contentContainer .contentContainerTitle span {
  font-size: 12px;
  color: #666;
}

.linepAdd .contentContainer .van-field__control,
.linepAdd .contentContainerp .van-field__control {
  background-color: #f8f8f8;
  padding: 10px;
  border-radius: 8px;
}

.linepAdd .contentContainer .van-cell,
.linepAdd .contentContainerp .van-cell {
  padding: 0;
}

.colorbalck {
  color: #333333;
}

.collapsettitle .van-cell__title {
  color: #333;
}

.van-dialog__confirm,
.van-dialog__confirm:active {
  color: #0057ba;
}

.colorRed {
  color: red;
}
</style>
