<template>
  <!--表单-->
  <div id="work-form">
    <el-form
      :model="param"
      ref="formData"
      :rules="rules"
      label-position="left"
      label-width="90px"
    >
      <el-row v-show="!$route.query.projectId" :gutter="20">
        <el-col :span="6">
          <el-form-item label="报告类型" prop="workType">
            <el-select
              v-model="param.workType"
              filterable
              @change="workTypetime"
              style="width: 100%"
            >
              <el-option
                v-for="item in options"
                :key="item.vaule"
                :label="item.key"
                :value="item.vaule"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" style="padding-right: 0">
          <el-form-item label="" prop="workType" label-width="0px">
            <el-date-picker
              v-if="this.param.workType == 'week'"
              style="width: 100%"
              @change="changeweek"
              v-model="value1"
              type="week"
              format="yyyy 第 WW 周"
              placeholder="选择周"
              :picker-options="{'firstDayOfWeek': 1}"
            ></el-date-picker>
            <el-date-picker
              v-if="this.param.workType == 'daily'"
              style="width: 100%"
              v-model="value1"
              type="date"
              @change="timesum"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              :picker-options="{'firstDayOfWeek': 1}"
            ></el-date-picker>
            <season-time
              v-if="this.param.workType == 'season'"
              @change="seasonData"
              v-model="value1"
            ></season-time>
            <el-date-picker
              v-if="this.param.workType == 'year'"
              style="width: 100%"
              v-model="value1"
              @change="timesum"
              value-format="yyyy"
              type="year"
              placeholder="选择年"
            ></el-date-picker>
            <el-date-picker
              v-if="this.param.workType == 'month'"
              style="width: 100%"
              v-model="value1"
              @change="timesum"
              type="month"
              value-format="yyyy-MM"
              placeholder="选择月"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

	  <el-row>
	    <el-col :span="12">
	     <el-form-item label="拜访报告">
         <div class="input-box">
           <div v-for="(item,index) in param.citeVisitCodes" :key="item.value"   class="wrap">
            <span    @click="toVisitDetail(item.value)">{{item.key}} </span>
            <el-button @click="removeData(index)" type="text" size="mini"  icon="el-icon-circle-close"></el-button>
            <!-- <i ></i> -->
          </div>
         </div>
	     </el-form-item>
	    </el-col>
      <el-col :span="12" style="padding-top: 5px; padding-left: 10px;">
        <el-button type="text" size="mini" style="color: red;" @click="visitData">点击查看拜访报告</el-button>
      </el-col>
	  </el-row>

      <el-row v-if="$route.query.projectId">
        <el-col :span="12">
          <el-form-item label="进展主题" prop="theme"
            ><el-input
              show-word-limit
              maxlength="100"
              v-model="param.theme"
              placeholder="请输入"
            ></el-input
          ></el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="知会人员"
            class="item-people"
            prop="personnelData"
          >
            <aws-org
              v-model="personnelData"
              @change="personnelDataChange"
              :isDialog="true"
              :sid="sid"
              :editable="openType == 'view' ? false : true"
              ref="awsorgRef"
              @submit="coordination"
            ></aws-org>
          </el-form-item>
        </el-col>
      </el-row>
      <!--主要内容部分-->
      <el-row>
        <el-col :span="24" class="main-info">
          <template v-for="(workSum, index) in param.workSumList">
            <el-form-item
              :label="index === 0 ? '工作总结' :'' " prop="workSumList">
              <div style="display: flex;align-items: center;">
                <el-input
                  show-word-limit
                  maxlength="300"
                  :autosize="{ minRows: 1, maxRows: 4}"
                  type="textarea"
                  v-model="workSum.content"
                  :placeholder="index + 1 + '.'"
                ></el-input>
                <el-button
                  type="text"
                  size="mini"
                  @click="addDomain"
                  v-if="index == 0"
                  icon="el-icon-circle-plus-outline"
                  ></el-button
                >
                <el-button
                  type="text"
                  @click="removeDomain(workSum)"
                  v-if="index !== 0"
                  icon="el-icon-remove-outline"
                ></el-button>
              </div>
            </el-form-item>
          </template>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24" class="main-info">
          <template v-for="(workPlan, index) in param.workPlanList">
            <el-form-item
              :label="index === 0 ? '工作计划' :'' " prop="workPlanList">
              <div style="display: flex;align-items: center;">
                <el-input
                  show-word-limit
                  maxlength="300"
                  type="textarea"
                  :autosize="{ minRows: 1, maxRows: 4}"
                  v-model="workPlan.content"
                  :placeholder="index + 1 + '.'"
                  style="flex: 1"
                ></el-input>
                <el-button
                  type="text"
                  size="mini"
                  @click="addDomainto"
                  v-if="index == 0"
                  icon="el-icon-circle-plus-outline"
                  ></el-button
                >
                <el-button
                  type="text"
                  @click="removeDomainto(workPlan)"
                  v-if="index !== 0"
                  icon="el-icon-remove-outline"
                ></el-button>
              </div>
            </el-form-item>
          </template>
        </el-col>
      </el-row>
    </el-form>
    <cite-visits ref="visitDialog" :isDialog="true" @visitrow="getVisitData"></cite-visits>
  </div>
</template>

<script>
import commonSelectList from "../../../../common/commonSelectList.js";
import citeVisits from '../../../../components/citeVisits.vue'//引用拜访dialog组件
import seasonTime from "./seasonTime.vue";
export default {
  name: "addWorkForm",
  props: {
    getParam: {
      type: Object,
      default: () => {},
      required: true,
    },
  },
  data() {
    return {
      url:'',
      labelWidth: "85px", //label宽度
      selectLabelWidth: "72.5px",
      seletWeekValue: "",
      weekTime: "",
      startTimeNum: "",
      endTimeNum: "",
      currentTime: "",
      TypeStatus:[],
      visitrow:[],
      param: {
        citeVisitCodes:[],//引用拜访报告
        deptId: "",
        deptName: "",
        id: "",
        notifyNames: "",
        notifyUids: "",
        informerParamList: [],
        planText: "",
        reviewerId: "",
        reviewerName: "",
        reviewerResult: "",
        summary: "",
        superiorName: "",
        superiorUid: "",
        workType: "daily",
        workTypeKey:'日报',
        workYearSuffix: "",
        workPlanList: [
          {
            content: "",
          },
          {
            content: "",
          },
          {
            content: "",
          },
        ],
        workSumList: [
          {
            content: "",
          },
          {
            content: "",
          },
          {
            content: "",
          },
        ],
        user: "",
        region: "",
        value1: "",
        status: "",
        dateParam: "",
        theme: "", //进展主题，项目详情，新增进展时 使用
      },
      timetype: "daily",
      options: [],
      typetime: "",
      personnelData: [],
      openType: "",
      value1: "",
      value2: "",
      rules: {
        workType: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        workPlanList: [{
          required: true,
          message: '请输入'
        }],
        workSumList: [{
          required: true,
          message: '内容不能为空'
        }],
        theme: [
          {
            required: true,
            message: "请输入",
          },
        ],
      },
    };
  },
  components: {
    seasonTime,
    citeVisits
  },
  created() {
    this.param.workType = "daily";
    this.opData();
    this.getNowTime();
    this.getHeadUrl();
    if(this.param.id==null||this.param.id===''){
      this.getDefaultVisit();
    }
  },
  methods: {
    getHeadUrl(){
       let headUrl = location.href;
       let index = headUrl .lastIndexOf("/");
       this.url =  headUrl .substring(0, index+1);
    },
    //获取当前用户当天默认选中的拜访报告
    getDefaultVisit(time) {
      console.log("time===>",time)
      let ext5 = '';
      if(time==null){
         ext5 = 'default';
      }
      let projectParam = {
        currPage: 1,
        pageSize: 100,
        queryParam: {
          unDraftFlag: 'draft',
          createrId:'byUid',
          ext5:ext5,
          createStartTime:time,
          createEndTime:time,
        }
      }
      this.$ajax.post({
        domain: 'crmUrl',
        url: 'visit.visitReportListByStatus',
        data: projectParam,
        requestType: 'body',
        showLoad: true,
        success: function(res) {
          if (res.errorCode === 200) {
            let dataInfo = res.data.records || [];
            let visitCodes = []
            if(dataInfo!=null&&dataInfo.length>0){
                dataInfo.forEach(item=>{
                   visitCodes.push({
                     key:item.visitCode,
                     value:item.id
                   })
                })
            }
            if(this.param.id==null||this.param.id===''){
              this.param.citeVisitCodes = visitCodes
            }
          }
        }.bind(this),
        error: function(res) {
          this.$message({
            type: 'error',
            message: res.body.msg || res.msg
          })
        }.bind(this)
      })
    },
    //引用拜访报告跳转
    toVisitDetail(row){
        console.log("row info ==>",row)
        if (row === null||row==='') {
          return;
        }
        let visitId = "visitId="+row;
        let route = "detailsVisit?"
        let param = route+visitId;
        window.open(this.url+param);
    },
    //调用关联拜访dialog组件
    visitData() {
      this.$refs.visitDialog.visible = true;
      // this.$refs.visitDialog.clearVisit([]);
    },
    removeData(index){
        console.log("index====>",index)
        this.param.citeVisitCodes.splice(index,1);
    },
    // 关闭拜访回调
    getVisitData (visitrow) {
      console.log("visitrow===>",visitrow)
      if(visitrow!=null&&visitrow.length>0){
        let visitCodes = this.param.citeVisitCodes
        visitrow.forEach(item=>{
           visitCodes.push({
             key:item.visitCode,
             value:item.id
           });
        })
        console.log("visitCodes==>",visitCodes)
        let newarr= this.unique(visitCodes);
        this.param.citeVisitCodes = newarr
      }
      this.$refs.visitDialog.visible = false;
    },
    unique(arr) {
     const res = new Map();
     return arr.filter((arr) => !res.has(arr.key) && res.set(arr.key, 1));
    },
    //子组件校验，传递到父组件
    validataForm() {
      let flag = null;
      this.$refs["formData"].validate((valid) => {
        if (valid) {
          flag = true;
        } else {
          flag = false;
        }
      });
      console.log("flag==============>", flag);
      return flag;
    },
    //知会人修改
    personnelDataChange(val) {
      if (this.param.informerParamList.length > 0) {
        this.param.informerParamList = this.param.informerParamList.filter(
          (item) => {
            for (let row of this.personnelData) {
              if (item.userId === row.uid) {
                return true;
              }
            }
          }
        );
      }
    },
    // 获取当前时间
    getNowTime() {
      console.log("报告类型==============》", this.param.workType);
      let dateTime;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      dateTime = yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
      this.value1 = dateTime;
      this.currentTime = yy + "" + mm + "" + dd;
      this.param.dateParam = dateTime;
      console.log(this.value1);
      console.log(this.currentTime);
    },
    workTypetime(val) {
      switch (val) {
        case "month":
          console.log(`月报`);
          // this.value1 = new Date()
          this.timesum();
          // 返回 yyyy-mm格式
          var month = this.param.dateParam;
          var monthStrs = month.split(" ");
          var yearMonthDay = monthStrs[0].split("-");
          var yearMonth = yearMonthDay[0] + "-" + yearMonthDay[1];
          this.param.dateParam = yearMonth;
          break;
        case "year":
          // console.log(`年报`)
          // this.value1 = new Date()
          this.timesum();
          // 返回 yyyy-mm格式
          var month = this.param.dateParam;
          var monthStrs = month.split(" ");
          var yearMonthDay = monthStrs[0].split("-");
          var year = yearMonthDay[0];
          this.param.dateParam = year;
          break;
        case "season":
          console.log(`季报`);
          // this.value1 = new Date()
          this.getNowTime();
          break;
        case "week":
          console.log(`周报`);
          // this.value1 = new Date()
          this.changeweek();
          break;
        case "daily":
          console.log(`日报`);
          // this.value1 = new Date()
          this.timesum();
          break;
        default:
      }
      // this.paramList()
    },
    // 时间戳转换为时间
    timestampToTime(timestamp) {
      var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      let Y = date.getFullYear() + "-";
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let D = date.getDate() + " ";
      return Y + M + D;
    },
    //周选择器开始时间和结束时间
    changeweek(val) {
      // this.value1 = val
      if (val == null || val == undefined) {
        val = new Date(this.value1.replace(/\-/g, "/"));
      }
      let firstDay = new Date(val.getFullYear(), 0, 1); // 2021-10-08
      let dayOfWeek = firstDay.getDay(); // 2021-10-08是周五  dayOfWeek==3
      let spendDay = 1;
      if (dayOfWeek != 0) {
        spendDay = 7 - dayOfWeek + 1; // 5 离下周一还有5天
      }
      firstDay = new Date(val.getFullYear(), 0, 1 + spendDay); // 2021-01-06是2020年第一个周一，是2020年第二个周
      let d = Math.ceil((val.valueOf() - firstDay.valueOf()) / 86400000); // 当前时间距离2020-01-06有几天
      let result = Math.ceil(d / 7); // 换算成周为单位 2020-01-06result是0,但其实是第二个周，所以默认加2
      let year = val.getFullYear();
      // let week = result + 1; //如果使用的是默认为加2（如果将自然周设置为周一到周日则是加1）
      let week = result; //如果使用的是默认为加2（如果将自然周设置为周一到周日则是加1）
      //console.log(week)
      let startTime = this.timestampToTime(val.valueOf() - 86400000); // 时间戳转字符串，$util是我们封装的方法
      let endTime = this.timestampToTime(val.valueOf() + 5 * 86400000);
      // this.weekTime = startTime+'~'+endTime+'  第'+week+'周'   // 2020-05-10~2020-05-16 第20周
      this.param.dateParam = year + "-" + week;
      this.paramList();
    },
    timesum() {
      this.param.dateParam = this.value1;
      this.paramList();
    },
    seasonData(data) {
      this.param.dateParam = data;
    },
    async opData() {
      this.options = await commonSelectList.initDictDataGet(
        this,
        "Crm_Report_Type"
      );
    },
    //根据监听判断父组件有没有值 有值的话则是编辑状态 接收数据并赋值渲染
    typeData(param) {
      this.param = param;
      let informerListArr = this.param.informerList || [];
      Object.assign(this.param, {
        ...this.param,
        workPlanList: this.param.workPlanList || this.param.workPlanList,
        workSumList: this.param.workSumList || this.param.workSumList,
      });
      switch (this.param.workType) {
        case "月报":
          this.param.workType = "month";
          break;
        case "年报":
          // console.log(`年报`)
          this.param.workType = "year";
          break;
        case "季报":
          console.log(`季报`);
          this.param.workType = "season";
          break;
        case "周报":
          // console.log(`周报`)
          this.param.workType = "week";

          break;
        case "日报":
          this.param.workType = "daily";
          break;
        default:
      }

      //this.param.workType = this.param.workType;
      this.param.informerParamList = this.param.informerList;
      if (this.param.weekDateTime) {
        this.value1 = this.param.weekDateTime;
      } else {
        this.value1 = this.param.dateParam;
      }
      for (var i = 0; i < informerListArr.length; i++) {
        this.personnelData.push({
          uid: informerListArr[i].userId,
          name: informerListArr[i].userName,
          email: informerListArr[i].email,
          informerType: 1,
        });
      }
      console.log("this.personnelData的值是：", this.personnelData);
      this.$nextTick(() => {
        let personnel=[];
        Object.assign(personnel,this.personnelData);
        this.$refs.awsorgRef.reset(personnel);
      });
      let arr = Object.keys(this.param.workPlanList);
      let arr2 = Object.keys(this.param.workSumList);
      if (arr.length == 0) {
        this.param.workPlanList = [
          { content: "" },
          { content: "" },
          { content: "" },
        ];
      }
      if (arr2.length == 0) {
        this.param.workSumList = [
          { content: "" },
          { content: "" },
          { content: "" },
        ];
      }

      console.log(this.param.workPlanList);
      //workPlanList
      // let usersArr = [...new Set(this.personnelData)];
      // //调用组织架构:编辑调用,添加不调用
      // this.$nextTick(() => {
      //   this.$refs.awsorgRef.reset(usersArr);
      // });
      this.$emit("formData", this.param);
    },

    removeDomain(item) {
      var index = this.param.workSumList.indexOf(item);
      if (index !== -1) {
        this.param.workSumList.splice(index, 1);
      }
    },
    removeDomainto(item) {
      var index = this.param.workPlanList.indexOf(item);
      if (index !== -1) {
        this.param.workPlanList.splice(index, 1);
      }
    },
    handleButton(data) {
      console.log(data);
    },
    addDomain() {
      this.param.workSumList.push({
        value: "",
        key: Date.now(),
      });
    },
    addDomainto() {
      this.param.workPlanList.push({
        value: "",
        key: Date.now(),
      });
    },
    //获取协同人员信息 这是子组件
    coordination(data, cord = []) {
      let arr = cord;
      for (var i = 0; i < this.personnelData.length; i++) {
        arr.push({
          userId: this.personnelData[i].uid,
          userName: this.personnelData[i].name,
          email: this.personnelData[i].email,
          informerType: 1,
        });
      }
      this.param.informerParamList = arr;
      console.log(this.param.informerParamList, 333333);
      this.paramList();
    },
    paramList() {
      if(this.param.workType === 'daily'){
            if(this.param.dateParam!=null&&this.param.dateParam!=''){
              this.getDefaultVisit(this.param.dateParam)
         }
      }
      this.$emit("formData", this.param);
    },
  },
  watch: {
    // 'getParam': {
    //   handler(val) {
    //     // console.log(val)
    //     this.typeData()
    //     // this.$nextTick(() => {
    //       // console.log('formData', this.param, val)
    //     // })
    //   },
    //   immediate: true
    // },
    param: {
      handler(val) {
        console.log("param", val);
        if ("param".length != 0) {
          this.paramList();
        }
      },
    },
  },
  computed: {
    sid() {
      return this.$common.getUrlParams("sid");
    },
  },
};
</script>

<style lang="scss">
#work-form{
  .item-people {
    .el-form-item__label {
      padding-left: 10px;
    }
  }
  .el-textarea__inner {
    padding-right: 55px;
  }
  .el-form--label-left .el-form-item__label {
    text-align: right;
  }
  .main-info{
    .el-form-item{
      margin-bottom: 5px;
    }
    i {
      font-size: 20px;
      margin-left: 5px;
    }
  }
  .input-box {
    display: flex;
    flex-wrap: wrap;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    min-height: 32px;
    line-height: 32px;
    padding: 0 15px;
    cursor: pointer;
    color:black;
    color:#0077FA;
    text-decoration: underline;
    .wrap{
      position: relative;
      margin-right: 20px;
    }
    span{
      text-decoration: underline;
      &:hover{
        color: #0077FA;
      }

    }
    .el-button{
      position: absolute;
      right: -15px;
      top: -10px;
      font-size: 15px;
    }
  }
}
</style>
