<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <div>
      <div v-if="inputForm.status === '5'&&(tabName === '一级校审'||tabName === '二级校审'||tabName === '三级校审')">
        <el-row type="flex" justify="end">
          <el-button @click="downloadFirstAuditTpl">下载</el-button>
        </el-row>
        <el-divider content-position="left"><i class="el-icon-document"></i> 项目校审</el-divider>
      </div>
      <el-form size="middle" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="formReadOnly"
               label-width="125px" @submit.native.prevent>
          <el-row  :gutter="15">
            <el-col :span="12">
              <el-form-item label="项目名称" prop="programProjectListInfo.name"
              >
                <el-input size="medium" :disabled="true" v-model="inputForm.programProjectListInfo.name" placeholder="请输入项目名称" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="评估基准日" prop="programProjectListInfo.assessmentDate"
              >
                <el-date-picker
                  :disabled="true"
                  v-model="inputForm.programProjectListInfo.assessmentDate"
                  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="12">
              <el-form-item label="专业评估人员" prop="auditPeopleList"
                            :rules="[{required: true, message: '专业评估人员不能为空', trigger: 'blur'},{required: true, message: '专业评估人员不能为空', trigger: 'change'}]"
              >
                <UserSelect size="medium" :disabled="formReadOnly" :readonly="true" :limit='10' :value="inputForm.auditPeopleList" @getValue='(value) => {inputForm.auditPeopleList = value}'></UserSelect>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目负责人" prop="programProjectListInfo.projectManager"
              >
                <SelectUserTree
                  ref="companyTree"
                  size="medium"
                  :props="{
                  value: 'id',             // ID字段名
                  label: 'name',         // 显示名称
                  children: 'children'    // 子级字段名
                }"
                  :url="`/sys/user/treeUserDataAllOffice?type=2`"
                  :value="inputForm.programProjectListInfo.projectManager"
                  :disabled="true"
                  :clearable="true"
                  :accordion="true"
                  @getValue="(value) => {inputForm.programProjectListInfo.projectManager=value}"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="选择项目审核人" prop="auditPeople"
                            :rules="[{required: true, message: '审批人不能为空', trigger: 'blur'},{required: true, message: '审批人不能为空', trigger: 'change'}]"
              >
                <UserSelect size="medium" :disabled="formReadOnly" :readonly="true" :limit='1' :value="inputForm.auditPeople" @getValue='(value) => {inputForm.auditPeople = value}'></UserSelect>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider content-position="left"><i class="el-icon-document"></i> 审核意见及回复</el-divider>
          <el-row>
            <el-col :span="24">
              <el-form-item label="明细表" prop="detailOpinion"
              >
                <!--            <el-input type="textarea" style="width:100%" maxlength="1000" v-model="inputForm.detailOpinion" placeholder="请填写明细表"     ></el-input>-->
                <WangEditor ref="contents1Editor" v-model="inputForm.detailOpinion"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="评估报告" prop="reportOpinion"
              >
                <!--            <el-input type="textarea" style="width:100%" maxlength="1000" v-model="inputForm.reportOpinion" placeholder="请填写评估报告"     ></el-input>-->
                <WangEditor ref="contents2Editor" v-model="inputForm.reportOpinion"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="技术说明" prop="remarksOpinion"
              >
                <!--            <el-input type="textarea" style="width:100%" maxlength="1000" v-model="inputForm.remarksOpinion" placeholder="请填写技术说明"     ></el-input>-->
                <WangEditor ref="contents3Editor" v-model="inputForm.remarksOpinion"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="工作底稿" prop="workOpinion"
              >
                <!--            <el-input type="textarea" style="width:100%" maxlength="1000" v-model="inputForm.workOpinion" placeholder="请填写工作底稿"     ></el-input>-->
                <WangEditor ref="contents4Editor" v-model="inputForm.workOpinion"/>
              </el-form-item>
            </el-col>
            <el-form size="middle" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"
                     label-width="125px" @submit.native.prevent>
              <el-col :span="24">
                <el-form-item label="执行人员保留意见" prop="retainOpinion"
                              :rules="[
                 ]">
                  <el-input type="textarea" :rows="5" maxlength="500" v-model="inputForm.retainOpinion" placeholder="请填写执行人员保留意见"     ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="审核人员审核未修改意见" prop="changeOpinion"
                              :rules="[
                 ]">
                  <el-input type="textarea" :rows="5"  maxlength="500" v-model="inputForm.changeOpinion" placeholder="请填写审核人员审核未修改意见"     ></el-input>
                </el-form-item>
              </el-col>
            </el-form>
          </el-row>


      </el-form>
      <!--        附件-->
      <UpLoadComponent ref="uploadComponent"></UpLoadComponent>

    </div>
  </div>
</template>

<script>
  import UpLoadComponent from '@/views/common/UpLoadComponent'
  import UserSelect from '@/components/userSelect'
  import SelectUserTree from '@/views/modules/utils/treeUserSelect'
  import RosterSelectForm from '@/views/common/RosterSelectForm'
  import ProgramProjectListInfoService from '@/api/program/ProgramProjectListInfoService'
  import WangEditor from '@/components/editor/WangEditorNoMenu'
  export default {
    props: {
      businessId: {
        type: String,
        default: ''
      },
      formReadOnly: {
        type: Boolean,
        default: false
      },
      status: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        title: '',
        method: '',
        visible: false,
        loading: false,
        inputForm: {
          id: '',
          remarks: '',
          programId: '',
          auditLevel: '',
          auditPeople: '',
          auditDate: '',
          retainOpinion: '',
          changeOpinion: '',
          detailOpinion: '',
          reportOpinion: '',
          remarksOpinion: '',
          workOpinion: '',
          procInsId: '',
          processDefinitionId: '',
          status: '',
          programProjectListInfo: {},
          programAuditAssessPeopleDtoList: [],
          workAttachmentDtoList: [],
          auditPeopleList: ''
        },
        programId: '',
        supervisorList: [],
        keyWatch: '',
        tabName: ''
      }
    },
    programProjectListInfoService: null,
    created () {
      this.programProjectListInfoService = new ProgramProjectListInfoService()
    },
    computed: {
      bus: {
        get () {
          this.$refs.uploadComponent.setDividerName('附件')
          return this.businessId
        },
        set (val) {
          this.businessId = val
        }
      }
    },
    watch: {
      'keyWatch': {
        handler (newVal) {
          if (this.bus) {
            if (this.bus !== 'false') {
              this.init('', this.bus)
            }
          } else {
            this.$nextTick(() => {
              this.$refs.inputForm.resetFields()
            })
          }
        }
      }
    },
    components: {
      UpLoadComponent,
      RosterSelectForm,
      UserSelect,
      WangEditor,
      SelectUserTree
    },
    methods: {
      getKeyWatch (keyWatch) {
        this.keyWatch = keyWatch
      },
      init (method, id, tabName) {
        this.tabName = tabName
        if (method === 'formReadOnly') {
          this.formReadOnly = true
        }
        this.method = method
        this.inputForm = {
          id: '',
          remarks: '',
          programId: '',
          auditLevel: '',
          auditPeople: '',
          auditDate: '',
          retainOpinion: '',
          changeOpinion: '',
          detailOpinion: '',
          reportOpinion: '',
          remarksOpinion: '',
          workOpinion: '',
          procInsId: '',
          processDefinitionId: '',
          status: '',
          programProjectListInfo: {
            id: ''
          },
          programAuditAssessPeopleDtoList: [],
          workAttachmentDtoList: [],
          auditPeopleList: ''
        }
        this.inputForm.id = id
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          this.loading = true
          this.programProjectListInfoService.findByIdAudit(this.inputForm.id).then(({data}) => {
            this.inputForm = this.recover(this.inputForm, data)
            this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
            this.$refs.contents1Editor.clear()
            this.$refs.contents2Editor.clear()
            this.$refs.contents3Editor.clear()
            this.$refs.contents4Editor.clear()
            this.$refs.uploadComponent.clearUpload()
            if (this.commonJS.isNotEmpty(this.inputForm.detailOpinion)) {
              this.$refs.contents1Editor.init(this.inputForm.detailOpinion)
            }
            if (this.commonJS.isNotEmpty(this.inputForm.reportOpinion)) {
              this.$refs.contents2Editor.init(this.inputForm.reportOpinion)
            }
            if (this.commonJS.isNotEmpty(this.inputForm.remarksOpinion)) {
              this.$refs.contents3Editor.init(this.inputForm.remarksOpinion)
            }
            if (this.commonJS.isNotEmpty(this.inputForm.workOpinion)) {
              this.$refs.contents4Editor.init(this.inputForm.workOpinion)
            }

            if (this.commonJS.isEmpty(this.inputForm.workAttachmentDtoList)) {
              this.inputForm.workAttachmentDtoList = []
            }
            if (this.commonJS.isNotEmpty(this.inputForm.programAuditAssessPeopleDtoList)) {
              let p = ''
              this.inputForm.programAuditAssessPeopleDtoList.forEach((item, index) => {
                if (this.inputForm.programAuditAssessPeopleDtoList.length === parseInt(parseInt(index) + parseInt(1))) {
                  p = p + item.assessPeople
                } else {
                  p = p + item.assessPeople + ','
                }
              })
              this.inputForm.auditPeopleList = p
            } else {
              this.inputForm.auditPeopleList = ''
            }
            if (this.formReadOnly === true && this.status === 'taskFormDetail') {
              this.$refs.uploadComponent.newUpload('view', this.inputForm.workAttachmentDtoList, 'program_audit')
            } else if (this.formReadOnly === true && this.status === 'audit') {
              this.$refs.uploadComponent.newUpload('view', this.inputForm.workAttachmentDtoList, 'program_audit', 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, 'program_audit')
            } else {
              this.$refs.uploadComponent.newUpload('view', this.inputForm.workAttachmentDtoList, 'program_audit', null, null, true, JSON.parse(localStorage.getItem('user')).name)
            }
            this.loading = false
          })
        })
      },
      saveForm (callback) {
        this.doSubmit('save', callback)
      },
      startForm (callback) {
        this.doSubmit('start', callback)
      },
      async agreeForm (callback) {
        await this.programProjectListInfoService.findByIdAudit(this.inputForm.id).then(({data}) => {
          if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            throw new Error()
          } else {
            this.doSubmit('agree', callback)
          }
        })
      },
      // 表单提交
      async doSubmit (status, callback) {
        if (await this.$refs.uploadComponent.checkProgress()) {
          this.loading = false
          throw new Error()
        }
        if (status === 'save') {
          // 暂存
          this.loading = true
          this.inputForm.status = '1'
          this.inputForm.workAttachmentDtoList = this.$refs.uploadComponent.getDataList()
          if (this.commonJS.isNotEmpty(this.inputForm.auditPeopleList)) {
            this.inputForm.programAuditAssessPeopleDtoList = []
            this.inputForm.auditPeopleList.split(',').forEach(item => {
              let i = {assessPeople: item, auditId: this.inputForm.id}
              this.inputForm.programAuditAssessPeopleDtoList.push(i)
            })
          } else {
            this.inputForm.programAuditAssessPeopleDtoList = []
          }
          this.programProjectListInfoService.saveFormThree(this.inputForm).then(({data}) => {
            this.inputForm.assignee = this.inputForm.auditPeople
            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') {
          // 审核同意
          this.inputForm.status = '5'
          this.inputForm.auditDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
        }
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            if (this.commonJS.isNotEmpty(this.inputForm.auditPeopleList)) {
              this.inputForm.programAuditAssessPeopleDtoList = []
              this.inputForm.auditPeopleList.split(',').forEach(item => {
                let i = {assessPeople: item, auditId: this.inputForm.id}
                this.inputForm.programAuditAssessPeopleDtoList.push(i)
              })
            } else {
              this.inputForm.programAuditAssessPeopleDtoList = []
            }
            this.inputForm.workAttachmentDtoList = this.$refs.uploadComponent.getDataList()
            this.programProjectListInfoService.saveFormThree(this.inputForm).then(({data}) => {
              this.inputForm.assignee = this.inputForm.auditPeople
              callback(data.businessTable, data.businessId, this.inputForm)
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          }
        })
      },
      async updateStatusById (type) {
        if (await this.$refs.uploadComponent.checkProgress()) {
          this.loading = false
          throw new Error()
        }
        await this.programProjectListInfoService.findByIdAudit(this.inputForm.id).then(({data}) => {
          if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            throw new Error()
          } else {
            // if (type === 'agree') {
            //   // 同意
            //   this.inputForm.status = '5'
            // }
            if (type === 'reject') {
              // 驳回
              this.inputForm.status = '4'
              this.loading = true
              this.inputForm.workAttachmentDtoList = this.$refs.uploadComponent.getDataList()
              if (this.commonJS.isNotEmpty(this.inputForm.auditPeopleList)) {
                this.inputForm.programAuditAssessPeopleDtoList = []
                this.inputForm.auditPeopleList.split(',').forEach(item => {
                  let i = {assessPeople: item, auditId: this.inputForm.id}
                  this.inputForm.programAuditAssessPeopleDtoList.push(i)
                })
              } else {
                this.inputForm.programAuditAssessPeopleDtoList = []
              }
              this.programProjectListInfoService.saveFormThree(this.inputForm).then(({data}) => {
                this.loading = false
              }).catch(() => {
                this.loading = false
              })
              return
            }
            if (type === 'reback') {
              // 撤回
              this.inputForm.status = '3'
            }
            if (type === 'reback') {
              let param = {status: this.inputForm.status, id: this.inputForm.id}
              this.programProjectListInfoService.updateStatusByAuditId(param)
            }
          }
        })
      },
      close () {
        this.$refs.uploadComponent.clearUpload()
        this.inputForm = {
          id: '',
          remarks: '',
          programId: '',
          auditLevel: '',
          auditPeople: '',
          auditDate: '',
          retainOpinion: '',
          changeOpinion: '',
          detailOpinion: '',
          reportOpinion: '',
          remarksOpinion: '',
          workOpinion: '',
          procInsId: '',
          processDefinitionId: '',
          status: '',
          programProjectListInfo: {},
          programAuditAssessPeopleDtoList: [],
          workAttachmentDtoList: []
        }
        this.$refs.inputForm.resetFields()
        this.visible = false
      },
      // 下载一级校审
      downloadFirstAuditTpl () {
        // this.$utils.downloadExcel('/sys/project/import/template')
        this.loading = true
        if (this.tabName === '一级校审') {
          this.programProjectListInfoService.downloadFirstAuditTpl(this.inputForm.programProjectListInfo.id, this.inputForm.id).then((res) => {
            // 将二进制流文件写入excel表，以下为重要步骤
            this.$utils.downloadWord(res.data, this.tabName)
            this.loading = false
          }).catch(function (err) {
            this.loading = false
            if (err.response) {
              console.log(err.response)
            }
          })
        }
        if (this.tabName === '二级校审') {
          this.programProjectListInfoService.downloadSecondAuditTpl(this.inputForm.programProjectListInfo.id, this.inputForm.id).then((res) => {
            // 将二进制流文件写入excel表，以下为重要步骤
            this.$utils.downloadWord(res.data, this.tabName)
            this.loading = false
          }).catch(function (err) {
            this.loading = false
            if (err.response) {
              console.log(err.response)
            }
          })
        }
        if (this.tabName === '三级校审') {
          this.programProjectListInfoService.downloadThirdlyAuditTpl(this.inputForm.programProjectListInfo.id, this.inputForm.id).then((res) => {
            // 将二进制流文件写入excel表，以下为重要步骤
            this.$utils.downloadWord(res.data, this.tabName)
            this.loading = false
          }).catch(function (err) {
            this.loading = false
            if (err.response) {
              console.log(err.response)
            }
          })
        }
      }
    }
  }
</script>
<style scoped>
  /deep/ .w-e-text-container {
    z-index: 1 !important;
  }
  /deep/ .wtext {
    height: 200px
  }
</style>
