<template>
  <div class="ls-vertical">
    <navbar icon="back" :title="openTitle" :back-func="backCallBack" :buttons="btns" @clickbutton="clickbtn"></navbar>
    <div class="ls-container">
      <!--表单部分-->
      <Form ref="myForm" :getParam="getParam" @formData="formData"></Form>
      <div class="upload-box">
        <p>附件上传</p>
        <ls-upload v-model="fileList" ref="uploadRef"></ls-upload>
      </div>
      <div class="ls-btn-row">
        <span class="c77FA" style="font-weight: bold;">相关任务</span>
        <div>
          <el-button @click="addtask" icon="el-icon-plus" type="primary" size="mini">新建任务</el-button>
          <el-button @click="projectReport" icon="el-icon-s-claim" type="primary" size="mini">引用任务</el-button>
        </div>
      </div>
      <div>
        <el-table class="todo-table dic-table" size="mini" stripe border :data="tableData" :cell-style="cellStyle">
          <el-table-column type="index" width="50" label="序号"></el-table-column>
          <el-table-column
            v-for="(item, index) in colunms"
            :key="index"
            :prop="item.prop"
            :label="item.label"
            :min-width="item.width"
            :show-overflow-tooltip="item.tooltip"
            :fixed="item.fixed"
          ></el-table-column>
          <el-table-column label="操作" min-width="100">
            <template slot-scope="scope">
              <el-button v-if="scope.row.status != 'draft' && scope.row.ext1 != 'add'" type="text" @click="deleteWorkDraft(scope.row, scope.$index)">解绑</el-button>
              <el-button v-if="scope.row.status == 'draft' && scope.row.ext1 != 'import'" @click="editDetail(scope.row, scope.$index)" type="text">编辑</el-button>
              <el-button v-if="scope.row.status == 'draft' && scope.row.ext1 != 'import'" @click="deleteWork(scope.row, scope.$index)" type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <dig-task-list ref="digTaskListRef" :modelId="3103" :preservationData="false" :hideedit="false" @taskData="addtaskData"></dig-task-list>
      <project-report ref="project" @taskData="addproject"></project-report>
    </div>
  </div>
</template>

<script>
import Form from './components/Form.vue';
import projectReport from './components/projectReport.vue';
import lsUpload from '../../../components/ls-upload.vue';
import commonSelectList from '../../../common/commonSelectList.js';
export default {
  name: 'addWork',
  components: {
    Form,
    projectReport,
    lsUpload
  },
  data() {
    return {
      btns: [
        {
          title: '保存',
          btnEvent: '',
          size: 'mini',
          btnEvent: 'draft',
          circle: false,
          type: 'primary',
          isplain: true,
          show: true,
          disabled: false,
          icon: 'el-icon-check'
        },
        {
          title: '提交',
          btnEvent: '',
          size: 'mini',
          btnEvent: 'unread',
          circle: false,
          type: 'primary',
          show: true,
          disabled: false,
          icon: 'el-icon-upload2'
        }
      ],
      param: {},
      hideDelete: true,
      projectId: '', //项目id
      getParam: {},
      datas: [],
      reviewStatus: [],
      workRow: {},
      fileData: '',
      attachFileInfoList: [],
      queryParam: {},
      fileList: [],
      pager: {
        curPage: 1,
        pageSize: 10,
        pageOptions: [10, 20, 50],
        totals: 0
      },
      showType: 'btn',
      multipleSelection: [],
      tableData: [],
      openTitle: '',
      //表格列
      colunms: [
        {
          prop: 'itemTypeKey',
          label: '事项类型',
          width: 100,
          fixed: false,
          tooltip: true
        },
        {
          prop: 'taskContent',
          label: '任务描述',
          width: 100,
          fixed: false,
          tooltip: true
        },
        {
          prop: 'taskUser',
          label: '责任人',
          width: 100,
          fixed: false,
          tooltip: true
        },
        {
          prop: 'userNamesStr',
          label: '协同人员',
          width: 100,
          fixed: false,
          tooltip: true
        },
        {
          prop: 'emergencyDegreeKey',
          label: '紧要程度',
          width: 100,
          fixed: false,
          tooltip: true
        },
        {
          prop: 'taskRequestDateFormat',
          label: '截至时间',
          width: 100,
          fixed: false,
          tooltip: true
        },
        {
          prop: 'projectCode',
          label: '关联项目',
          width: 100,
          fixed: false,
          tooltip: true
        },
        {
          prop: 'visitReportCode',
          label: '关联拜访报告',
          width: 100,
          fixed: false,
          tooltip: true
        },

        {
          prop: 'statusKey',
          label: '状态',
          width: 100,
          fixed: false,
          tooltip: true
        }
      ]
    };
  },
  created() {
    this.projectId = this.$route.query.projectId ? this.$route.query.projectId : ''; //从 项目编辑，新增进展进来时
    this.initDict();
    this.reviewData();
  },
  methods: {
    cellStyle({ row, column, rowIndex, columnIndex }) {
      let cellStyle;
      if (column.label === '状态') {
        switch (row.status) {
          case 'draft':
            cellStyle = '';
            break;
          case 'finish':
            cellStyle = 'color: #67C23A;';
            break;
          case 'cancel':
            cellStyle = 'color: #909399;';
            break;
          default:
            cellStyle = 'color: #409EFF;';
        }
      }
      return cellStyle;
    },
    addtaskData(data) {
      debugger;
      let addtask = data;
      addtask.ext1 = 'add';
      if (addtask.tableid == null || addtask.tableid == undefined) {
        this.tableData.push(addtask);
      } else {
        //如果有tableid的话代表是编辑,则把前面table的对应tableid删除
        this.tableData.forEach((child, index) => {
          if (addtask.tableid === index) {
            this.tableData.splice(index, 1);
            addtask.ext1 = 'add';
          }
        });
        this.tableData.push(addtask);
      }
    },
    addproject(data) {
      debugger;
      let addtask = data;
      let arrpro = [];
      addtask.forEach(child => {
        child.ext1 = 'import';
        this.tableData.forEach((item, index) => {
          item.id === child.id && this.tableData.splice(index, 1);
        });
        this.tableData.push(child);
      });
    },
    //编辑任务数据
    editDetail(row, i) {
      this.$refs.digTaskListRef.visible = true;
      this.$refs.digTaskListRef.openTitle = '编辑';
      this.$refs.digTaskListRef.editDetail(row, i);
    },
    deleteWorkDraft(row, i) {
      this.$confirm('是否解绑该数据?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        .then(() => {
          //解绑数据
          if (row.ext1 == 'import' && (row.relevanceWorkNumber == null || row.relevanceWorkNumber == '')) {
            this.tableData.splice(i, 1);
          } else {
            let param = { id: row.id };
            this.$ajax.post({
              domain: 'crmUrl',
              url: 'work.unfastenWorkOrTaskBind',
              data: JSON.stringify(param),
              success: function(res) {
                if (res.errorCode == 200) {
                  this.tableData.splice(i, 1);
                } else {
                  this.$message({
                    message: res.data.msg,
                    type: 'warning'
                  });
                }
              }.bind(this)
            });
          }
        })
        .catch(() => {
          this.$message({
            message: res.data.msg,
            type: 'error'
          });
        });
    },
    //移除引用的数据或删除草稿状态的数据
    deleteWork(row, i) {
      let rowData = row;
      this.$confirm('是否删除该数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          //移除数据
          if (row.id == null || row.id == '') {
            this.tableData.splice(i, 1);
          } else {
            let param = [rowData.id];
            this.$ajax.post({
              domain: 'crmUrl',
              url: 'task.deleteTasks',
              data: JSON.stringify(param),
              success: function(res) {
                if (res.errorCode == 200) {
                  this.tableData.splice(i, 1);
                } else {
                  this.$message({
                    message: res.data.msg,
                    type: 'warning'
                  });
                }
              }.bind(this),
              error: function(res) {
                this.$message({
                  message: res.data.msg,
                  type: 'warning'
                });
              }.bind(this)
            });
          }
        })
        .catch(() => {
          this.$message({
            message: res.data.msg,
            type: 'error'
          });
        });
    },
    async initDict() {
      this.reviewStatus = await commonSelectList.initDictDataGet(this, 'Crm_ReviewStatus');
      this.TypeStatus = await commonSelectList.initDictDataGet(this, 'Crm_Report_Type');
    },
    //获取批阅状态
    reviewData() {
      this.param = {};
      this.workRow = this.$route.query.rowData;
      if (this.workRow) {
        Object.assign(this.param, this.workRow); // 这里有一个
        this.openTitle = this.projectId ? this.$route.query.openTitle : '修改报告';
        this.getWorkDetail(this.workRow);
      } else if (this.projectId) {
        this.openTitle = this.$route.query.openTitle;
      } else {
        this.openTitle = '写报告';
      }
    },
    backCallBack() {
      // this.$confirm('确定离开当前页面?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      if (this.projectId) {
        this.$router.push({
          name: 'projectDetail',
          params: { projectId: this.projectId, activeTab: 'projectProgress' }
        });
      } else {
        this.$router.back(-1);
      }
      // }).catch(() => { });
    },
    getWorkDetail(workRow) {
      let para = {
        id: workRow.id,
        projectId: this.projectId ? this.projectId : ''
      };
      this.$ajax.post({
        domain: 'crmUrl',
        url: 'work.getWorkDetail',
        data: JSON.stringify(para),
        success: res => {
          if (res.errorCode === 200) {
            this.getParam = res.data;
            if (res.data.taskInfoList) {
              this.tableData = res.data.taskInfoList;
            }
            this.hideDelete = false;
            let arr1 = res.data.workPlanList;
            let arr2 = res.data.workSumList;
            let workPlanList = [];
            let workSumList = [];
            let arrfile = [];
            for (var i = 0; i < this.getParam.attachFileInfoList.length; i++) {
              arrfile.push({
                name: this.getParam.attachFileInfoList[i].fileName,
                size: this.getParam.attachFileInfoList[i].fileSize,
                response: {
                  data: {
                    fileSize: this.getParam.attachFileInfoList[i].fileSize,
                    fileName: this.getParam.attachFileInfoList[i].fileName,
                    fileId: this.getParam.attachFileInfoList[i].fileId
                  }
                }
              });
            }
            // //需要遍历过滤一遍 只保留content 其它不保留
            for (var i = 0; i < arr1.length; i++) {
              workPlanList.push({
                content: arr1[i].content
              });
            }
            //需要遍历过滤一遍 只保留content 其它不保留
            for (var i = 0; i < arr2.length; i++) {
              workSumList.push({
                content: arr2[i].content
              });
            }
            this.fileList = arrfile;
            this.$refs.uploadRef.reset(this.fileList);
            this.getParam.workPlanList = workPlanList;
            this.getParam.workSumList = workSumList;
            this.param = this.getParam;
            this.$refs.myForm.typeData(this.getParam);
          } else {
            this.$message.error(res.msg);
          }
        }
      });
    },
    doQuery() {},
    //新建任务
    addtask() {
      this.$refs.digTaskListRef.visible = true;
      this.$refs.digTaskListRef.openTitle = '新建任务';
    },
    //引用项目报告
    projectReport() {
      this.$refs.project.visible = true;
      this.$refs.project.openTitle = '引用报告';
    },
    canceladd() {
      this.$router.go(-1);
    },
    clickbtn(type) {
      console.log(type);
      switch (type) {
        case 'cancel':
          this.canceladd();
          break;
        case 'draft':
          this.$refs['myForm'].paramList();
          this.submitWork('draft');
          break;
        case 'unread':
          this.$refs['myForm'].paramList();
          this.submitWork('unread');
          break;
      }
    },
    //保存
    submitWork(workStatus) {
      console.log('this.param===>', this.param);
      if (!this.checkData(this.param)) {
        return;
      }
      let flag = this.$refs['myForm'].validataForm();
      if (flag) {
        let arr = [];
        for (var i = 0; i < this.fileList.length; i++) {
          arr.push({
            fileId: this.fileList[i].response.data.fileId,
            fileName: this.fileList[i].response.data.fileName,
            fileSize: this.fileList[i].response.data.fileSize
          });
        }
        this.param.attachFileInfoList = arr;
        if (this.projectId) {
          this.param.projectId = this.projectId;
          this.param.theme = this.$refs.myForm.param.theme;
          this.param.reportBigType = 'projectReport';
        } else {
          this.param.reportBigType = 'workReport';
        }
        this.param.reviewStatus = workStatus;
        //添加任务
        this.param.taskParamList = this.tableData;
        this.param.workPlanList.map((v, i) => {
          v.contentSort = i + 1;
        });
        this.param.workSumList.map((v, i) => {
          v.contentSort = i + 1;
        });
        let successMsg = '成功';
        this.btns[0].disabled = true;
        this.btns[1].disabled = true;
        if (this.param.reviewStatus != null && this.param.reviewStatus != '') {
          if (this.param.reviewStatus == 'draft') {
            successMsg = '保存成功!';
          } else {
            successMsg = '提交成功!';
          }
        }
        this.$ajax.post({
          domain: 'crmUrl',
          url: 'work.saveOrUpdateWorkReport',
          data: JSON.stringify(this.param),
          showLoad: false,
          success: function(res) {
            if (res.errorCode === 200) {
              this.$message.success(successMsg);
              //跳转
              this.backCallBack();
            }
          }.bind(this),
          complete: function() {
            this.btns[0].disabled = false;
            this.btns[1].disabled = false;
          }.bind(this)
        });
      }
    },
    checkData(data) {
      data = this.param;
      let flag = true;

      let plan = 0;
      data.workPlanList.forEach(item => {
        if (item.content) {
          plan += 1;
        }
      });
      if (plan === 0) {
        this.$message('工作计划不能为空');
        flag = false;
      }

      let sum = 0;
      data.workSumList.forEach(item => {
        if (item.content) {
          sum += 1;
        }
      });
      if (sum === 0) {
        this.$message('工作总结不能为空');
        flag = false;
      }

      if (this.projectId && !this.$refs.myForm.param.theme) {
        this.$message.error('请输入进展主题');
        flag = false;
      }
      return flag;
    },

    formData(data) {
      Object.assign(this.param, data);
      setTimeout(() => {
        console.log('data', this.param);
      }, 3000);
    },
    upData() {
      this.$refs.uploadRef.visible = true;
    }
  }
};
</script>

<style scoped lang="scss">
.ls-container {
  border-top: 1px solid #f4f4f4;
  margin: 0px;
  padding: 20px;
  overflow: auto;

  .ls-btn-row {
    padding: 10px 0;
  }
}
</style>

<style lang="scss">
.updata {
  border: 1px solid #ebebeb;
  background-color: #e4e7ed;
  width: 100px;
  height: 100px;
}

.updata i {
  margin: 0px 45%;
  line-height: 100px;
}

.el-table .el-table__empty-block {
  min-height: 0px;
}

.upload-box {
  border-top: 4px solid #f0f0f0;
  margin: 10px -20px 0;
  padding: 20px;

  > p {
    margin-bottom: 14px;
    font-size: 14px;
    font-weight: bold;
    color: #0077fa;
  }
}
</style>
