<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <el-form size="middle" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="formReadOnly"
             label-width="120px" @submit.native.prevent>
      <el-divider content-position="left"><i class="el-icon-document"></i> 业务提问信息</el-divider>
      <el-row  :gutter="15">
        <el-col :span="12">
          <el-form-item label="标题" prop="title"
                        :rules="[
                        {required: true, message: '标题不能为空', trigger: 'blur'},{required: true, message: '标题不能为空', trigger: 'change'}
                 ]">
            <el-input v-model="inputForm.title" placeholder="请填写标题" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="问题类型" prop="type"
                        :rules="[
                        {required: true, message: '问题类型不能为空', trigger: 'blur'},{required: true, message: '问题类型不能为空', trigger: 'change'}
                        ]">
            <el-select v-model="inputForm.type" placeholder="请选择问题类型" clearable style="width: 100%;">
              <el-option
                v-for="item in $dictUtils.getDictList('question_type')"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
<!--        项目名称-->
        <el-col :span="12">
          <el-form-item label="所属项目" prop="programName"
                        :rules="[
                 ]">
            <el-input @focus="openProgramPageForm()" :disabled="formReadOnly || (belongFlag !== 1 && belongFlag !== 2)" :readonly="true" v-model="inputForm.programName" placeholder="请选择项目" clearable>
              <el-button slot="append" :disabled="formReadOnly || (belongFlag !== 1 && belongFlag !== 2)" @click="openProgramPageForm" icon="el-icon-search"></el-button>
            </el-input>
          </el-form-item>
        </el-col>
<!--        选择审核人  多选-->
        <el-col :span="12">
          <el-form-item label="问题处理人员" prop="disposeBy"
                        :rules="[{required: true, message: '问题处理人员不能为空', trigger: 'blur'},{required: true, message: '问题处理人员不能为空', trigger: 'change'}]"
          >
            <UserSelect size="medium" :disabled="formReadOnly" :readonly="true" :limit='10' :value="inputForm.disposeBy" @getValue='(value) => {inputForm.disposeBy = value}'></UserSelect>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="期望完成时间" prop="expectFinishDate"
                        :rules="[
                 ]">
            <el-date-picker
              v-model="inputForm.expectFinishDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择期望完成时间"
              style="width:100%"
              placement="bottom-start"
              clearable>
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="问题内容" prop="content"
          >
            <WangEditor ref="contentEditor" v-model="inputForm.content"
                        @getUrl="(url, lsUrl) => {
                        inputForm.editorFilesDTOList.push({temporaryUrl: lsUrl, url: url});
                        }"/>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-for="(item,index) in inputForm.klgBaseReplyDTOList">
          <el-form-item :label="commonJS.isNotEmpty(item.replyName)?item.replyName+'回复：':'回复：'"
                        :prop="'content'+index"
          >
            <WangEditor ref="contentEditorList" :index="index" v-model="item.content"
                        @getUrl="getUrl"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!--        附件-->
    <UpLoadComponent ref="uploadComponent"></UpLoadComponent>
    <ProgramPageForm ref="programPageForm" @getProgram="getProgram"></ProgramPageForm>
  </div>
</template>

<script>
  import UpLoadComponent from '@/views/common/UpLoadComponent'
  import SelectUserTree from '@/views/modules/utils/treeUserSelect'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import UserSelect from '@/components/userSelect'
  import KlgBaseQuestionsService from '@/api/klgBase/questions/KlgBaseQuestionsService'
  import ProgramPageForm from './ProgramPageForm'
  import WangEditor from '@/components/editor/WangEditor'
  import OfficeService from '@/api/sys/OfficeService'
  export default {
    props: {
      businessId: {
        type: String,
        default: ''
      },
      formReadOnly: {
        type: Boolean,
        default: false
      },
      status: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        title: '',
        method: '',
        loading: false,
        inputForm: {
          title: '',
          type: '',
          programId: '',
          programName: '',
          disposeBy: '',
          expectFinishDate: '',
          content: '',
          status: '',
          procInsId: '',
          processDefinitionId: '',
          editorFilesDTOList: [],
          klgBaseDisposeDTOList: [],
          klgBaseReplyDTOList: [],
          workAttachmentDtoList: [],
          projectType: ''
        },
        keyWatch: '',
        belongFlag: ''
      }
    },
    klgBaseQuestionsService: null,
    officeService: null,
    created () {
      this.klgBaseQuestionsService = new KlgBaseQuestionsService()
      this.officeService = new OfficeService()
    },
    computed: {
      bus: {
        get () {
          this.$refs.uploadComponent.setDividerName('附件')
          // this.$refs.contentEditor.clear()
          return this.businessId
        },
        set (val) {
          this.businessId = val
        }
      }
    },
    watch: {
      'keyWatch': {
        handler (newVal) {
          if (this.commonJS.isNotEmpty(this.bus)) {
            this.init('', this.bus)
          } else {
            this.$nextTick(() => {
              this.$refs.inputForm.resetFields()
            })
          }
        }
      }
    },
    components: {
      SelectUserTree,
      UpLoadComponent,
      SelectTree,
      UserSelect,
      ProgramPageForm,
      WangEditor
    },
    methods: {
      getKeyWatch (keyWatch) {
        this.keyWatch = keyWatch
      },
      init (method, id) {
        this.klgBaseQuestionsService = new KlgBaseQuestionsService()
        this.officeService = new OfficeService()
        this.officeService.checkLoginIsPgOrKj().then(({data}) => {
          this.belongFlag = data
        })
        this.method = method
        this.inputForm = {
          title: '',
          type: '',
          programId: '',
          programName: '',
          disposeBy: '',
          expectFinishDate: '',
          content: '',
          status: '',
          procInsId: '',
          processDefinitionId: '',
          editorFilesDTOList: [],
          klgBaseDisposeDTOList: [],
          klgBaseReplyDTOList: [],
          workAttachmentDtoList: [],
          projectType: ''
        }
        this.inputForm.id = id
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          this.loading = true
          this.$refs.contentEditor.clear()
          this.klgBaseQuestionsService.queryById(this.inputForm.id).then(({data}) => {
            if (this.status === 'audit') {
              this.$refs.contentEditor.disable()
            } else {
              this.$refs.contentEditor.enable()
            }
            this.$refs.uploadComponent.clearUpload()
            this.inputForm = this.recover(this.inputForm, data)
            this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
            if (this.commonJS.isNotEmpty(this.inputForm.content)) {
              this.$refs.contentEditor.init(this.inputForm.content)
            }
            if (this.commonJS.isEmpty(this.inputForm.editorFilesDTOList)) {
              this.inputForm.editorFilesDTOList = []
            }
            if (this.commonJS.isEmpty(this.inputForm.workAttachmentDtoList)) {
              this.inputForm.workAttachmentDtoList = []
            }
            if (this.formReadOnly === true && this.status === 'taskFormDetail') {
              this.$refs.uploadComponent.newUpload('view', this.inputForm.workAttachmentDtoList, 'klg_questions')
            } else if (this.formReadOnly === true && this.status === 'audit') {
              this.$refs.uploadComponent.newUpload('view', this.inputForm.workAttachmentDtoList, 'klg_questions', null, null, true, JSON.parse(localStorage.getItem('user')).name)
            } else if (this.formReadOnly === true && this.status !== 'audit' && this.status !== 'taskFormDetail') {
              this.$refs.uploadComponent.newUpload('view', this.inputForm.workAttachmentDtoList, 'klg_questions')
            } else {
              this.$refs.uploadComponent.newUpload('view', this.inputForm.workAttachmentDtoList, 'klg_questions', null, null, true, JSON.parse(localStorage.getItem('user')).name)
            }
            this.$nextTick(() => {
              if (this.commonJS.isNotEmpty(this.inputForm.klgBaseReplyDTOList)) {
                if (this.status === 'audit') {
                  this.inputForm.klgBaseReplyDTOList.push({content: ''})
                }
                this.inputForm.klgBaseReplyDTOList.forEach((item, index) => {
                  if (this.commonJS.isNotEmpty(item.content)) {
                    this.$refs.contentEditorList[index].init(item.content)
                    this.$refs.contentEditorList[index].disable()
                  }
                })
              } else {
                this.inputForm.klgBaseReplyDTOList = []
                if (this.status === 'audit') {
                  this.inputForm.klgBaseReplyDTOList.push({content: ''})
                }
              }
            })
            this.loading = false
          })
        })
      },
      saveForm (callback) {
        this.doSubmit('save', callback)
      },
      startForm (callback) {
        this.doSubmit('start', callback)
      },
      async agreeForm (callback) {
        await this.klgBaseQuestionsService.queryById(this.inputForm.id).then(({data}) => {
          if (this.inputForm.procInsId !== data.procInsId) { // “procInsId”已经改变，就弹出提示
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            throw new Error()
          } else {
            this.doSubmit('agree', callback)
          }
        })
      },
      // 表单提交
      doSubmit (status, callback) {
        if (status === 'save') {
          // 暂存
          this.inputForm.status = '1'
          this.loading = true
          if (this.$refs.uploadComponent.checkProgress()) {
            this.loading = false
            return
          }
          this.inputForm.workAttachmentDtoList = this.$refs.uploadComponent.getDataList()
          if (this.commonJS.isNotEmpty(this.inputForm.disposeBy)) {
            this.inputForm.klgBaseDisposeDTOList = []
            this.inputForm.disposeBy.split(',').forEach(item => {
              let i = {disposeBy: item, questionId: this.inputForm.id}
              this.inputForm.klgBaseDisposeDTOList.push(i)
            })
          } else {
            this.inputForm.klgBaseDisposeDTOList = []
          }
          this.getEditorFilesDTOList()
          this.getEditorFilesDTOS()
          this.klgBaseQuestionsService.saveForm(this.inputForm).then(({data}) => {
            this.inputForm.assignee = this.inputForm.disposeBy
            callback(data.businessTable, data.businessId, this.inputForm)
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
          return
        } else if (status === 'start') {
          // 送审  待审核
          this.inputForm.status = '2'
        } else if (status === 'agree') {
          // 审核同意
          if (this.inputForm.status === '2') {
            this.inputForm.status = '5'
          } else if (this.inputForm.status === '5') {
            this.inputForm.finishDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
            this.inputForm.status = '6'
          }
        }
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            if (this.$refs.uploadComponent.checkProgress()) {
              this.loading = false
              return
            }
            this.inputForm.klgBaseReplyDTOList.forEach((item, index) => {
              if (this.commonJS.isEmpty(item.content)) {
                this.inputForm.klgBaseReplyDTOList.splice(index, 1)
              }
            })
            this.inputForm.workAttachmentDtoList = this.$refs.uploadComponent.getDataList()
            if (this.commonJS.isNotEmpty(this.inputForm.disposeBy)) {
              this.inputForm.klgBaseDisposeDTOList = []
              this.inputForm.disposeBy.split(',').forEach(item => {
                let i = {disposeBy: item, questionId: this.inputForm.id}
                this.inputForm.klgBaseDisposeDTOList.push(i)
              })
            } else {
              this.inputForm.klgBaseDisposeDTOList = []
            }
            this.getEditorFilesDTOList()
            this.getEditorFilesDTOS()
            this.klgBaseQuestionsService.saveForm(this.inputForm).then(({data}) => {
              if (this.inputForm.status === '2') {
                this.inputForm.assignee = this.inputForm.disposeBy
              }
              callback(data.businessTable, data.businessId, this.inputForm)
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          }
        })
      },
      async updateStatusById (type, callback) {
        if (await this.$refs.uploadComponent.checkProgress()) {
          this.loading = false
          throw new Error()
        }
        await this.klgBaseQuestionsService.queryById(this.inputForm.id).then(({data}) => {
          if (this.inputForm.procInsId !== data.procInsId) { // status的值不等于“审核中”，或者“procInsId”已经改变，就弹出提示
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            throw new Error()
          } else {
            // if (type === 'agree') {
            //   // 同意
            //   this.inputForm.status = '5'
            // }
            if (type === 'reject') {
              // 驳回
              this.loading = true
              if (this.$refs.uploadComponent.checkProgress()) {
                this.loading = false
                return
              }
              this.inputForm.workAttachmentDtoList = this.$refs.uploadComponent.getDataList()
              if (this.commonJS.isNotEmpty(this.inputForm.disposeBy)) {
                this.inputForm.klgBaseDisposeDTOList = []
                this.inputForm.disposeBy.split(',').forEach(item => {
                  let i = {disposeBy: item, questionId: this.inputForm.id}
                  this.inputForm.klgBaseDisposeDTOList.push(i)
                })
              } else {
                this.inputForm.klgBaseDisposeDTOList = []
              }
              this.inputForm.klgBaseReplyDTOList.forEach((item, index) => {
                if (this.commonJS.isEmpty(item.content)) {
                  this.inputForm.klgBaseReplyDTOList.splice(index, 1)
                }
              })
              if (this.inputForm.status === '2') {
                this.inputForm.status = '4'
              } else if (this.inputForm.status === '5') {
                this.inputForm.status = '2'
              }
              this.getEditorFilesDTOList()
              this.getEditorFilesDTOS()
              this.klgBaseQuestionsService.saveForm(this.inputForm).then(({data}) => {
                this.inputForm.assignee = this.inputForm.disposeBy
                callback(data.businessTable, data.businessId, this.inputForm)
                this.loading = false
              }).catch(() => {
                this.loading = false
              })
              return
            }
            if (type === 'reback') {
              // 撤回
              let param = {status: '3', id: this.inputForm.id}
              this.klgBaseQuestionsService.updateStatusById(param)
            }
          }
        })
      },
      close () {
        this.inputForm = {
          title: '',
          type: '',
          programId: '',
          programName: '',
          disposeBy: '',
          expectFinishDate: '',
          content: '',
          status: '',
          procInsId: '',
          processDefinitionId: '',
          editorFilesDTOList: [],
          klgBaseDisposeDTOList: [],
          klgBaseReplyDTOList: [],
          workAttachmentDtoList: [],
          projectType: ''
        }
        this.$refs.uploadComponent.clearUpload()
        this.$refs.inputForm.resetFields()
        this.$refs.contentEditor.enable()
      },
      openProgramPageForm () {
        if (this.belongFlag === '1' || this.belongFlag === 1) {
          this.$refs.programPageForm.init('1') // 评估部门人员打开
        } else if (this.belongFlag === '2' || this.belongFlag === 2) {
          this.$refs.programPageForm.init('2') // 兴光会计部门人员打开
        } // 其他人不允许打开
      },
      getProgram (row) {
        if (this.commonJS.isNotEmpty(row)) {
          this.inputForm.programId = row.id // 项目id
          this.inputForm.programName = row.name // 项目名称
          this.inputForm.projectType = row.ptype // 项目类型   兴光会计项目还是评估项目
        }
      },
      getEditorFilesDTOList () {
        let a = []
        if (this.commonJS.isNotEmpty(this.inputForm.editorFilesDTOList)) {
          this.inputForm.content = this.inputForm.content.replace(/&amp;/g, '&')
          this.inputForm.editorFilesDTOList.forEach((item) => {
            if (this.inputForm.content.includes(item.temporaryUrl)) {
              a.push(item)
            }
          })
        }
        this.inputForm.editorFilesDTOList = []
        a.forEach((item) => {
          this.inputForm.editorFilesDTOList.push(item)
        })
      },
      getEditorFilesDTOS () {
        if (this.commonJS.isNotEmpty(this.inputForm.klgBaseReplyDTOList)) {
          this.inputForm.klgBaseReplyDTOList.forEach((item, index) => {
            item.content = item.content.replace(/&amp;/g, '&')
            let a = []
            if (this.commonJS.isNotEmpty(item.editorFilesDTOList)) {
              item.editorFilesDTOList.forEach((item2) => {
                if (item.content.includes(item2.temporaryUrl)) {
                  a.push(item2)
                }
              })
            }
            this.inputForm.klgBaseReplyDTOList[index].editorFilesDTOList = []
            a.forEach((item) => {
              this.inputForm.klgBaseReplyDTOList[index].editorFilesDTOList.push(item)
            })
          })
        }
      },
      getUrl (url, lsUrl, index) {
        if (this.commonJS.isEmpty(this.inputForm.klgBaseReplyDTOList[index].editorFilesDTOList)) {
          this.inputForm.klgBaseReplyDTOList[index].editorFilesDTOList = []
        }
        this.inputForm.klgBaseReplyDTOList[index].editorFilesDTOList.push({temporaryUrl: lsUrl, url: url})
      }
    }
  }
</script>
<style scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
  /deep/ .w-e-text-container {
    z-index: 1 !important;
  }
  /deep/ .w-e-menu {
    z-index: 2 !important;
  }
  /deep/ .wtext {
    height: 400px
  }
</style>
