<template>
  <div class="editPublishTask">
    <section class="main-section pubconfig">
      <div v-if="showEmpty">
        <header>
          <headTitle title="checklist" />
        </header>
        <div class="empty">
          未设置 <span class="createBtn" @click="addAction">点击添加</span>
        </div>
      </div>
      <div v-else>
        <header>
          <headTitle title="checklist" :open-edit="openEdit" @editHandle="editHandle" />
        </header>
        <div class="wrap">
          <redTipword title="关联任务" :isedit="edit" />
          <multipleSelect placeholder="🔍 请输入任务名称或ID" :isedit="edit" :data="data.tasks" :task-id="taskId" @change="changeTask" />
          <div v-if="edit" style="margin-top: 30px">
            <redTipword title="选择checklist列表" :isedit="edit" />
            <checkboxList :selected-list="data.selectedBizTemplateIds" :data="temList" @change="updateSelectedTemHandle" />
          </div>
        </div>
        <div class="moduleList wrap">
          <redTipword v-if="!edit" title="检查项" :isedit="edit" />
          <div v-for="(item, index) in data.templates" :key="item.parentTemplateId" class="item">
            <div v-if="item.type === 1" style="width: 690px">
              <p :id="`s${item.parentTemplateId}`" class="title">
                <el-checkbox v-if="!edit" v-model="item.isCheck" :label="item.name" @change="updateCheckItemHandle(item)">{{ item.name }}</el-checkbox>
                <span v-else>{{ item.name }}</span>
              </p>
              <onlineCheckList
                :module-id="item.parentTemplateId"
                :isedit="edit"
                :data="item.onlineModule"
                :task-id="taskId"
                @changeSelectedHandle="changeOnlineSelectedHandle"
                @changeRow="changeOnlineModuleRow"
                @onChangeModuleName="(val, subIdx) => onChangeModuleName(val, subIdx, index)"
              />
            </div>
            <div v-else style="width: 690px">
              <p :id="`s${item.parentTemplateId}`" class="title">
                <el-checkbox v-if="!edit" v-model="item.isCheck" :label="item.name" @change="updateCheckItemHandle(item)">{{ item.name }}</el-checkbox>
                <span v-else>{{ item.name }}</span>
              </p>
              <normal-area
                v-if="edit"
                :id="'tem'+item.parentTemplateId"
                :value.sync="item.content"
                :empty-text="'点击'"
                :input-button="'修改模板'"
                :styles="{ padding: '0 0px 20px 0px', width: '690px' }"
              />
              <div v-else v-html="item.content" />
            </div>
          </div>
        </div>
        <div v-if="edit" class="control">
          <el-button size="small" @click="cancel()">取消</el-button>
          <el-button type="primary" size="small" @click="saveHandle()">
            保存
          </el-button>
        </div>
      </div>
    </section>
    <div v-if="!edit">
      <section class="main-section">
        <div>
          <headTitle title="动态" />
        </div>
        <actionDynamic :comments="commentlist" :change-record="changeRecordList" @addComment="createCommentHandle" />
      </section>
      <div v-if="!showEmpty" class="step">
        <step :data="data.templates" :type-list="data.templates" @goto="scrollToHandle" />
      </div>
    </div>
  </div>
</template>
<script>
const _ = require('lodash')
import redTipword from '@/components/redTipTitle'
import headTitle from '@/components/headTitle'
import multipleSelect from './components/multipleSelect'
import checkboxList from './components/checkboxList'
import onlineCheckList from './components/onlineCheckList'
import actionDynamic from '@/components/actionDynamic'
import step from './components/step'
// 富文本
// import textArea from '@/components/input/textArea'
import normalArea from '@/components/input/normalArea' // 富文本
import 'tinymce/plugins/table'// 插入表格插件
import store from '@/store'
import {
  getCheckListBytask,
  getBizBindTemList,
  updateChecklist,
  createChecklist,
  updateTemplateCheckStatus,
  getCommentList,
  createComment,
  getRecordList
} from '@/api/publishTask'
export default {
  components: {
    redTipword,
    multipleSelect,
    checkboxList,
    onlineCheckList,
    normalArea,
    headTitle,
    actionDynamic,
    step
  },
  props: {
    taskId: {
      type: Number,
      required: true,
      default: -1
    },
    taskName: {
      type: String,
      required: true,
      default: ''
    },
    userNames: {
      type: String,
      required: true,
      default: ''
    },
    userInformation: {
      type: String,
      required: true,
      default: ''
    }
  },
  data() {
    return {
      description: '<p style="color:red;">123</p>',
      edit: false, // 是否是编辑状态
      showEmpty: true,
      openEdit: true,
      data: {},
      temList: [],
      commentlist: [], // 评价列表
      changeRecordList: [], // 变更记录列表
      checkListId: -1
    }
  },
  mounted() {
    // 获取模板列表
    this.getBizBindTemList()
    // 获取checklist详情
    this.getList()
    // 获取评论列表
    this.getCommentList()
  },
  methods: {
    // 获取checklist详情
    async getList() {
      if (this.taskId) {
        const res = await getCheckListBytask({ taskId: this.taskId })
        // res.data = null
        if (res.data) {
          // 如果绑定过
          this.showEmpty = false
          this.data = res.data
          this.checkListId = res.data.id
          // 获取变更记录
          this.getRecordList()
        } else {
          this.showEmpty = true
        }
      }
    },

    // 获取业务线下绑定的可以选checklist列表
    async getBizBindTemList() {
      const { bizId = null } = store.state.global || {}
      const res = await getBizBindTemList({ name: '', bizId })
      this.temList = res.data
    },

    async getCommentList() {
      const res = await getCommentList({ type: 5, joinId: this.taskId })
      if (res.code === 200) {
        this.commentlist = res.data
      }
    },

    // 获取变更记录
    async getRecordList() {
      const res = await getRecordList({ checkListId: this.checkListId })
      if (res.code === 200) {
        this.changeRecordList = res.data
      }
    },
    // 添加评论
    async createCommentHandle(content, callback) {
      const commentInfo = {
        joinId: this.taskId,
        content,
        type: 5,
        fatherId: 0,
        name: this.userNames,
        email: this.userInformation
      }
      const user = { name: this.userNames, ename: this.userInformation, id: '' }
      const res = await createComment({ commentInfo, user })
      if (res.code === 200) {
        this.$message({ message: '评论成功', type: 'success', duration: 1000, offset: 150 })
        this.getCommentList()
        callback()
      } else {
        this.$message.warning(res.msg)
      }
    },

    // 添加或者删除线上模板的模版名
    changeOnlineSelectedHandle(id, subIdx, value, type) {
      /**
       * id: 模块id
       * name: 线上模块中哪个模块下的模块名称
       * value: 模块名
       * type: 是添加还是删除
      **/
      // const tem = this.data.templates
      this.data.templates.map(t => {
        if (t.parentTemplateId === id) {
          if (type === 'del') {
            t.onlineModule.onlineOrder = t.onlineModule.onlineOrder.filter(g => g !== value)
            t.onlineModule.tableContent.map((t, i) => {
              if (i === subIdx) {
                t.moduleNames = t.moduleNames.filter(g => g !== value)
              }
            })
          } else if (!t.onlineModule.onlineOrder.includes(value)) {
            t.onlineModule.onlineOrder.push(value)
            t.onlineModule.tableContent.map((t, i) => {
              if (i === subIdx) {
                t.moduleNames.push(value)
              }
            })
          } else {
            this.$message({
              message: '已经添加过该模块名称',
              type: 'error'
            })
          }
        }
      })
    },

    changeOnlineModuleRow(type, mId, index) {
      this.data.templates.map(t => {
        if (t.parentTemplateId === mId) {
          if (type === 'del') {
            const delModuleNames = t.onlineModule.tableContent[index].moduleNames
            t.onlineModule.onlineOrder = t.onlineModule.onlineOrder.filter(t => !delModuleNames.includes(t))
            t.onlineModule.tableContent.splice(index, 1)
          } else {
            t.onlineModule.tableContent.splice(index + 1, 0, {
              module: `模块${index + 1}`,
              moduleNames: []
            })
          }
        }
      })
    },

    // 保存
    async saveHandle() {
      if (this.data.tasks.length < 1) {
        this.$message({
          message: '请关联一个任务',
          type: 'error'
        })
        return
      }
      let res = null
      if (this.data.id) {
        res = await updateChecklist(this.data)
      } else {
        res = await createChecklist(this.data)
      }
      if (res.code === 200) {
        this.edit = false
        this.openEdit = true
        // 保存更新变更记录
        this.getRecordList()
        this.getList()
        this.$message({
          message: '保存成功',
          type: 'success'
        })
      }
    },

    // 取消
    cancel() {
      this.edit = false
      this.openEdit = true
      this.data = this.copyData
      if (!this.data || JSON.stringify(this.data) === '{}') {
        this.showEmpty = true
      }
    },
    // 点击添加
    addAction() {
      // 校验是否绑定过checklist模板
      if (!this.RegHasCheckListTem()) {
        return
      }
      // 复制一份数据，以便取消时复原
      this.copyData = this.data
      // 编辑按钮隐藏
      this.openEdit = false
      // 编辑状态打开
      this.edit = true
      // 是否显示空状态
      this.showEmpty = false
      this.data = {
        selectedBizTemplateIds: [],
        templates: [],
        tasks: [{
          id: this.taskId,
          name: this.taskName
        }]
      }
      this.checkAllTem()
    },

    // 编辑
    editHandle() {
      // 校验是否绑定过checklist模板
      if (!this.RegHasCheckListTem()) {
        return
      }
      // 复制一份数据，以便取消时复原
      this.copyData = this.data
      // 编辑状态打开
      this.edit = true
      // 编辑按钮隐藏
      this.openEdit = false
      this.checkAllTem()
    },

    // 添加和编辑checklist时 如果没有选择模版默认全选。
    checkAllTem() {
      const { selectedBizTemplateIds } = this.data
      if (!selectedBizTemplateIds || selectedBizTemplateIds.length < 1) {
        this.temList.map(t => {
          this.data.selectedBizTemplateIds.push(t.id)
          const { content, isCheck, name, onlineModule, type, id: parentTemplateId } = t
          this.data.templates.push({
            content,
            isCheck,
            name,
            onlineModule,
            type,
            parentTemplateId,
            belongType: 2 // checklist的模板
          })
        })
      }
    },

    // 校验是否该业务线有绑定checklist模板
    RegHasCheckListTem() {
      if (!this.temList || this.temList.length < 1) {
        this.$message({
          message: '该业务线暂无绑定checklist模板，请先绑定checklist模板',
          type: 'error'
        })
        return false
      } else {
        return true
      }
    },

    // 修改checklist绑定模版列表
    updateSelectedTemHandle(checkedIds) {
      const selectedBizTemplateIds = []
      const tems = []
      const { templates } = this.data
      // 循环都有哪些tem被选择了
      checkedIds.map(checkedId => {
        // 先循环是否有存过模板数据
        this.temList.map(g => {
          if (g.id === checkedId) {
            selectedBizTemplateIds.push(g.id)
            const { content, isCheck, name, onlineModule, type, id: parentTemplateId } = g
            tems.push({
              content,
              isCheck,
              name,
              onlineModule,
              type,
              parentTemplateId,
              belongType: 2 // checklist的模板
            })
          }
        })
      })
      tems.map((h, index) => templates.map(j => {
        if (h.parentTemplateId === j.parentTemplateId) {
          tems[index] = { ...j }
        }
      }))
      this.data = { ...this.data, templates: tems, selectedBizTemplateIds }
    },

    // 锚点
    scrollToHandle(targe) {
      const anchorH = document.getElementById(targe).offsetTop
      const container = document.getElementsByClassName('main-wrapper')[0]
      container.scrollTop = anchorH - 20
    },

    // 解绑删除任务
    changeTask(task, type) {
      let hasTask = false
      let tasks = []
      this.data.tasks.map(g => {
        if (g.id === task.id) {
          hasTask = true
        }
      })
      if (type === 'del') {
        tasks = this.data.tasks.filter(t => t.id !== task.id)
      } else if (!hasTask) {
        tasks = [...this.data.tasks, task]
      } else {
        this.$message({
          message: '已经添加过该任务',
          type: 'error'
        })
        return
      }
      this.data = { ...this.data, tasks }
    },

    // 更新检查项到数据库
    async updateCheckItemHandle(item) {
      const { isCheck, id } = item
      const res = await updateTemplateCheckStatus({ isCheck, id, checkListId: this.checkListId })
      if (res.code === 200) {
        this.getRecordList()
        this.$message({
          message: '检查项状态更新成功',
          type: 'success'
        })
      }
    },

    // 修改线上问题模块
    onChangeModuleName: _.debounce(function(val, subIdx, index) {
      this.data.templates[index].onlineModule.tableContent[subIdx].module = val
    })
  }
}
</script>
<style scoped lang="scss">
@import '@/styles/detail-pages.scss';
.editPublishTask {
  min-height: 400px;
  overflow-y: auto;
  padding-bottom: 20px;
  .step {
    position: fixed;
    top: 200px;
    right:150px;
  }
  .pubconfig {
    .control {
      padding: 20px 0px 20px 690px;
    }
  }
  .main-section {
    @include main-section;
  }
  .wrap{
    padding: 0 40px;
  }
  .moduleList {
    margin-top: 40px;
    padding-bottom: 16px;
    .title {
      font-weight: 400;
      color: #444444;
      font-size: 14px;
      margin-bottom: 16px;
      margin-top: 40px;
    }
  }
}
.empty {
  padding: 0px 30px 40px 30px;
  color: #444;
  font-size: 14px;
  .createBtn {
    color: #409EFF;
    margin-left: 5px;
    cursor: pointer;
  }
}
.main-title {
  @include main-title;
}
</style>
