<template>
  <div class="daily">
    <!--        顶部条-->
    <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="lineGrey"></div>
    <div class="lineGrey"></div>
    <div class="lineGrey"></div>
    <div class="lineGrey"></div>
    <div style="height: 4px"></div>
    <!--        主体内容-->
    <div class="container linepAdd">
      <template v-if="postName == '质感销售负责人' || postName == '质感销售专员'">
        <target :homePageIndicatorDate="homePageIndicatorList"></target>
      </template>
      <template v-else>
        <van-collapse v-model="activeNames" style="margin-top: -3px">
          <template v-if="!YFQuota">
            <template v-if="reportTarget.postType == 'GZ' || reportTarget.BMDType == 'BMD'">
              <!-- 0-历史指标  1-动态指标，String类型 -->
              <target
                v-if="reportTarget.targetType == '1'"
                :homePageIndicatorDate="homePageIndicatorList"></target>
              <template v-else>
                <!-- 历史指标 -->
                <Atarget :reportInfo="reportTarget"></Atarget>
                <Btarget :reportInfo="reportTarget"></Btarget>
              </template>
            </template>
            <template v-else>
              <!-- YFQuota:应用服务平台 不显示各项指标 -->
              <Atarget :reportInfo="reportTarget"></Atarget>
              <Btarget :reportInfo="reportTarget"></Btarget>
            </template>
          </template>
        </van-collapse>
      </template>
      <div class="contentContainer">
        <!-- isHistory 是否为历史汇报：0-新汇报 1-历史汇报 -->
        <reportCustom
          ref="reportCustom"
          v-if="reportTarget.isHistory == '0'"
          :reportCustomData="reportTarget.customTaskList"></reportCustom>
        <template v-else>
          <div v-if="GZQuota">
            <p class="contentContainerTitle">今日项目跟进数<span class="colorRed">(必填)</span></p>
            <div style="padding: 10px 0">
              <van-field v-model="reportContents[2].projectFollowNum" type="digit" />
            </div>
            <p class="contentContainerTitle">
              今日TUC成功报备数量<span class="colorRed">(必填)</span>
            </p>
            <div style="padding: 10px 0">
              <van-field v-model="reportContents[3].tucReportingSuccessNum" type="digit" />
            </div>
          </div>
          <div
            v-if="
              (this.$route.query.reportId && notVisitReason) || reportTarget.showNotVisitReason
            ">
            <p class="contentContainerTitle">
              截至日报提交时间，今日拜访0家店的原因<span class="colorRed">(必填)</span>
            </p>
            <div style="padding: 10px 0">
              <van-field
                v-model="notVisitReason"
                rows="3"
                autosize
                maxlength="1000"
                show-word-limit
                type="textarea"
                :formatter="formatter" />
            </div>
          </div>
          <p class="contentContainerTitle">
            今日机会与挑战总结<span class="colorRed">(必填)</span>
          </p>
          <div style="padding: 10px 0">
            <van-field
              v-model="reportContents[0].dayContent"
              rows="4"
              autosize
              maxlength="800"
              show-word-limit
              type="textarea"
              :formatter="formatter" />
          </div>
          <p class="contentContainerTitle">明日工作规划 <span class="colorRed">(必填)</span></p>
          <div style="padding: 10px 0">
            <van-field
              v-model="reportContents[1].dayContent"
              rows="4"
              autosize
              maxlength="800"
              show-word-limit
              type="textarea"
              :formatter="formatter" />
          </div>
        </template>
      </div>
      <br />
    </div>
    <div class="contentborder">
      <van-button type="info" size="small" plain class="Btn1" @click="submint">提交日报</van-button>
    </div>
    <div class="lineGrey"></div>
    <div class="lineGrey"></div>
    <div class="lineGrey"></div>
    <div class="lineGrey"></div>
  </div>
</template>

<script>
import {
  userTodayPlanNum,
  updateReport,
  getReportInfo,
  getDetailById,
  tsContents,
  buryingPoint,
  getSkuDetailById,
} from '@/api/index';
import visitedRealTime from '@/views/componentsTarget/visitedRealTime';
import createStoreBJ from '@/views/componentsTarget/createStoreBJ';
import placeOrder from '@/views/componentsTarget/placeOrder';
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 reportCustom from './reportCustom';
import target from './target.vue';
import Atarget from '@/views/home/Atarget.vue';
import Btarget from '@/views/home/Btarget.vue';

export default {
  name: 'daily',
  components: {
    visitedRealTime,
    createStoreBJ,
    placeOrder,
    ZYPlaceOrder,
    performanceSAP,
    ZYSAP,
    veryGoodPlaceOrder,
    reportCustom,
    target,
    Atarget,
    Btarget,
  },
  data() {
    return {
      show: true,
      num: 0,
      todayGoal: {},
      progressWidth: 0,
      activeNames: [
        '1',
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '16',
        '17',
        '20',
        '21',
        '22',
        '23',
        '29',
        '11',
        '33',
        '40',
        '41',
        '42',
        '43',
      ],
      powerGrade: '',
      value: '2',
      message: '',
      isclick: true,
      saptitle: '业绩目标SAP(千元)',
      reportTargetAll: {},
      reportTarget: {},
      temporaryShow: '',
      projectFollowNum: '',
      reportingNum: '',
      tucReportingSuccessNum: '',
      reportContents: [
        {
          dayContent: '',
          contentTime: '',
          type: 2,
          status: '1',
        },
        {
          dayContent: '',
          contentTime: '',

          type: 3,
          status: '1',
        },
        {
          dayContent: '',
          contentTime: '',
          projectFollowNum: '',
          type: 3,
          status: '1',
        },
        {
          dayContent: '',
          contentTime: '',
          tucReportingSuccessNum: '',
          type: 3,
          status: '1',
        },
      ],
      type: '-1',
      JZQuota: false, //家装
      GZQuota: false, //工装
      YFQuota: false, //应用服务
      titlejz: '',
      notVisitReason: '', //今日拜访0家店的原因；
      photoSkuImgSummaryeList: null,
      postName: '',
      homePageIndicatorList: null,
    };
  },
  created() {
    this.powerGrade = localStorage.getItem('powerGrade');
    this.temporaryShow = this.$route.query.temporaryShow;
    this.postName = localStorage.getItem('postName');
    this.homePageIndicatorList = null;
    if (this.$route.query.reportId != undefined) {
      this.getDetailById();
    } else {
      this.getReportInfo();
    }
  },
  watch: {
    $route(to, from) {
      this.powerGrade = localStorage.getItem('powerGrade');
      this.postName = localStorage.getItem('postName');
      if (to.path == '/daily') {
        this.temporaryShow = this.$route.query.temporaryShow;
        if (this.$route.query.reportId != undefined) {
          this.getDetailById();
        } else {
          this.notVisitReason = '';
          this.reportContents = [
            {
              dayContent: '',
              contentTime: '',
              type: 2,
              status: '1',
            },
            {
              dayContent: '',
              contentTime: '',

              type: 3,
              status: '1',
            },
            {
              dayContent: '',
              contentTime: '',
              projectFollowNum: '',
              type: 3,
              status: '1',
            },
            {
              dayContent: '',
              contentTime: '',
              tucReportingSuccessNum: '',
              type: 3,
              status: '1',
            },
          ];
          this.getReportInfo();
        }
      }
    },
  },
  methods: {
    // return value.replace(/[^\u4E00-\u9FA5|\d|\a-zA-Z|\r\n\s,.?!，。？！"…—（）&_%【】{}:“”‘#~@;：；￥$=()-+-·——/*{}[\]]|\r\n\s/g, '');
    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,
      });
      this.reportContents[0].dayContent = '';
      getDetailById({ reportId: this.$route.query.reportId }).then((res) => {
        loading1.clear();
        if (res.code == 200) {
          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;
            localStorage.setItem('powerGrade', res.data.positionId);
            localStorage.setItem('userDeptLevel', res.data.userDeptLevel);
            this.GZQuota = false;
            this.JZQuota = false;
            this.YFQuota = res.data.postType == 'YF' ? true : false;
            if (res.data.postType == 'JZ') {
              this.JZQuota = true;
            } else if (res.data.postType == 'GZ') {
              this.GZQuota = true;
              this.saptitle = '公裝业绩SAP(千元)';
            } else {
              this.saptitle = '业绩目标SAP(千元)';
            }
            if (this.reportTarget.projectFollowNum) {
              this.projectFollowNum = this.reportTarget.projectFollowNum;
              this.reportingNum = this.reportTarget.reportingNum;
              this.tucReportingSuccessNum = this.reportTarget.tucReportingSuccessNum;
            }

            this.type = res.data.userType;
            if (res.data.reportContents.length > 0) {
              this.reportContents = res.data.reportContents;
              if (res.data.reportContents.length < 2) {
                res.data.reportContents.push({
                  dayContent: '',
                  contentTime: '',
                  type: 3,
                  status: '1',
                });
              }
              if (res.data.reportContents.length > 2) {
                if (res.data.reportContents[2].projectFollowNum != null) {
                  this.projectFollowNum = res.data.reportContents[2].projectFollowNum;
                } else {
                  this.projectFollowNum = '';
                  res.data.reportContents[2].projectFollowNum = '';
                }
                if (res.data.reportContents[3].tucReportingSuccessNum != null) {
                  this.tucReportingSuccessNum = res.data.reportContents[3].tucReportingSuccessNum;
                } else {
                  this.tucReportingSuccessNum = '';
                  res.data.reportContents[3].tucReportingSuccessNum = '';
                }
              }
            }
            this.reportTargetAll = res.data.reportTargetAll;
            this.reportTarget = res.data;
            this.notVisitReason = this.reportTarget.notVisitReason;
          }
          this.getskuDetailByIdFun();
        } else {
          this.$toast(res.msg);
        }
      });
    },
    tsContentsFn() {
      this.toastLoading(0, '加载中...', true);
      if (this.isclick) {
        // 旧的
        if (this.reportTarget.isHistory == '1') {
          this.reportContents[0].contentTime = this.parseTime(new Date(), '{y}-{m}-{d}');
          this.reportContents[1].contentTime = this.parseTime(new Date(), '{y}-{m}-{d}');
          if (this.GZQuota) {
            this.reportContents[2].contentTime = this.parseTime(new Date(), '{y}-{m}-{d}');
            this.reportContents[3].contentTime = this.parseTime(new Date(), '{y}-{m}-{d}');
          }
          this.reportTarget.reportContents = this.reportContents;
          this.reportTarget.notVisitReason = this.notVisitReason;
          this.tsContentsFun();
        } else {
          // 新的
          if (this.reportTarget.customTaskList && this.reportTarget.customTaskList.length) {
            // 配置任务
            this.filterReportCustomData((reportCustomAnswers) => {
              this.tsContentsFun(reportCustomAnswers);
            });
          } else {
            // 没有配置任务
            this.tsContentsFun(null);
          }
        }
      }
    },
    tsContentsFun(reportCustomAnswers) {
      if (reportCustomAnswers) this.reportTarget.reportCustomAnswers = reportCustomAnswers;
      this.reportTarget.status = '1';
      this.isclick = false;
      tsContents(this.reportTarget).then((res) => {
        this.toastLoading().clear();
        this.isclick = true;
        if (res.code == 200) {
          this.$dialog
            .alert({
              title: '系统提示',
              message: '暂存成功',
            })
            .then(() => {});
        } else {
          this.$toast.fail(res.msg);
        }
      });
    },
    // 提交日报
    submint() {
      this.toastLoading(0, '加载中...', true);
      if (this.isclick) {
        // 旧的
        if (this.reportTarget.isHistory == '1') {
          if (this.GZQuota) {
            if (this.reportContents[2].projectFollowNum.trim() == '') {
              this.$toast('请输入今日项目跟进数量！');
              return false;
            }
            if (this.reportContents[3].tucReportingSuccessNum.trim() == '') {
              this.$toast('请输入今日TUC成功报备数量！');
              return false;
            }
          }
          if (
            (this.$route.query.reportId && this.notVisitReason) ||
            this.reportTarget.showNotVisitReason
          ) {
            if (this.notVisitReason.trim() == '') {
              this.$toast('请输入今日拜访0家店的原因！');
              return false;
            }
            this.reportTarget.notVisitReason = this.notVisitReason;
          }
          if (this.reportContents[0].dayContent.trim() == '') {
            this.$toast('请输入日报内容！');
            return false;
          } else if (this.reportContents[0].dayContent.length > 800) {
            this.$toast('日报内容太长！');
            return false;
          } else if (this.reportContents[1].dayContent.trim() == '') {
            this.$toast('请输入明日工作规划！');

            return false;
          } else if (this.reportContents[1].dayContent.length > 800) {
            this.$toast('明日工作规划内容太长！');
            return false;
          }
          this.reportContents[0].contentTime = this.parseTime(new Date(), '{y}-{m}-{d}');
          this.reportContents[1].contentTime = this.parseTime(new Date(), '{y}-{m}-{d}');
          if (this.GZQuota) {
            this.reportContents[2].contentTime = this.parseTime(new Date(), '{y}-{m}-{d}');
            this.reportContents[3].contentTime = this.parseTime(new Date(), '{y}-{m}-{d}');
          }
          this.reportTarget.reportContents = this.reportContents;
          this.submintFun();
        } else {
          // 新的
          if (this.reportTarget.customTaskList && this.reportTarget.customTaskList.length) {
            // 配置任务
            this.reportCustomTabstoreVal((reportCustomAnswers) => {
              this.submintFun(reportCustomAnswers);
            });
          } else {
            // 没有配置任务
            this.submintFun(null);
          }
        }
      }
    },
    submintFun(reportCustomAnswers) {
      this.reportTarget.status = '1';
      if (reportCustomAnswers) this.reportTarget.reportCustomAnswers = reportCustomAnswers;
      this.isclick = false;
      updateReport(this.reportTarget).then((res) => {
        this.toastLoading().clear();
        this.isclick = true;
        if (res.code == 200) {
          if (this.reportTarget.reportPostType == 'fx') {
            this.$dialog
              .alert({
                message: '已提交，是否分享',
                showCancelButton: true,
                confirmButtonText: '分享',
                cancelButtonText: '返回首页',
                className: 'dailyShareBtn',
              })
              .then(() => {
                buryingPoint({
                  systemModel: '日报审核',
                  buryingPointType: 2,
                  buryingPointValue: this.$route.query.reportId,
                  buryingPointName: '日报提交分享',
                  buryingPointPosition: '日报提交',
                });
                // 跳转历史汇报详情 分享汇报
                this.$router.replace({
                  path: 'dailyDetails',
                  query: { reportId: res.data, sourceType: 'daily' },
                });
              })
              .catch(() => {
                if (this.$route.query.reportId != undefined) {
                  window.location.replace(window.location.origin + this.locationOrigin + '/home');
                } else {
                  this.onClickLeft();
                }
              });
          } else {
            this.$dialog
              .alert({
                title: '系统提示',
                message: '提交成功',
              })
              .then(() => {
                if (this.$route.query.reportId != undefined) {
                  window.location.replace(
                    window.location.origin + this.locationOrigin + '/myHistoricalDaily',
                  );
                } else {
                  this.onClickLeft();
                }
              });
          }
        } 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);
    },
    // 获取日报数据
    getReportInfo() {
      let loading1 = this.$toast.loading({
        duration: 0,
        message: '加载中...',
        forbidClick: true,
      });
      this.reportContents[0].dayContent = '';
      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.type = res.data.userType;
        this.reportTargetAll = res.data.reportTargetAll;
        this.reportTarget = res.data;
        this.GZQuota = false;
        this.JZQuota = false;
        this.YFQuota = res.data.postType == 'YF' ? true : false;
        this.homePageIndicatorList = res.data.homePageIndicatorList;

        if (res.data.postType == 'JZ') {
          this.JZQuota = true;
        } else if (res.data.postType == 'GZ') {
          this.GZQuota = true;
          this.saptitle = '公裝业绩SAP(千元)';
        } else {
          this.saptitle = '业绩目标SAP(千元)';
        }
        if (res.data.reportContents && res.data.reportContents.length > 0) {
          this.reportContents = res.data.reportContents;
          if (res.data.reportContents.length > 2) {
            this.projectFollowNum = res.data.reportContents[2].projectFollowNum;
            this.tucReportingSuccessNum = res.data.reportContents[3].tucReportingSuccessNum;
          }
        }
        this.notVisitReason = res.data.notVisitReason;
        this.getskuDetailByIdFun();
      });
    },
    getskuDetailByIdFun() {
      if (this.reportTarget.reportPostType != 'fx') return;
      getSkuDetailById({ reportId: this.reportTarget.id }).then((res) => {
        if (res.code == 200) {
          this.photoSkuImgSummaryeList = res.data;
        } else {
          this.photoSkuImgSummaryeList = null;
        }
      });
    },
    userTodayPlanNum() {
      userTodayPlanNum().then((res) => {
        if (res.code == 200) {
          this.todayGoal = res.data;
          this.progressWidth = (this.todayGoal.finishNum / this.todayGoal.planNum) * 100 + '%';
          localStorage.setItem('nickName', res.data.user.nickName);
          localStorage.setItem('storeType', res.data.user.type);
        } else {
          this.$toast.fail(res.msg);
        }
      });
    },
    onClickLeft() {
      this.$router.push('/home');
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  margin: 10px;
}
.container .van-collapse-item {
  margin-bottom: 10px;
  border-radius: 6px;
  overflow: hidden;
}
.linepAdd p {
  margin: 6px 0 0 0;
  font-size: 14px;
  color: #666;
}

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

.linepAdd .texttitle2 {
  padding-left: 0;
}

.linepAdd .texttitle .opint {
  position: absolute;
  left: 0px;
  top: 6px;
  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 lang="scss">
.daily {
  .SKUTable {
    padding-bottom: 10px;
    .table-headermd1 {
      font-size: 12px;
      text-align: center;
      position: initial;
      width: 98% !important;
      margin: 0 auto;
      border-right: 0;
      border-radius: 10px;
      .el-table__cell {
        padding: 6px 0 !important;
      }
      thead {
        .el-table__cell {
          background-color: #1989fa;
          color: #fff;
        }
      }
    }
  }
}
.linepAdd .van-cell__title {
  color: #1e5398;
  font-weight: 500;
}
.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 {
  background-color: #f8f8f8;
  padding: 10px;
  border-radius: 8px;
}
.linepAdd .contentContainer .van-cell {
  padding: 0;
}
.van-dialog__confirm,
.van-dialog__confirm:active {
  color: #0057ba;
}
.linepAdd .contentContainer .contentContainerTitle .colorRed {
  color: red;
}
.dailyShareBtn {
  .van-dialog__confirm {
    // border: 1px solid #ccc;
    // border-bottom: none;
  }
  .van-hairline--left {
    background: #0057ba;
    color: #fff;
  }
}
</style>
