<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <div v-if="inputForm.status === '5'&&tabName === '报告签发单'">
      <el-row type="flex" justify="end">
        <el-button @click="downloadReportAusstellungTpl">下载</el-button>
      </el-row>
      <el-divider content-position="left"><i class="el-icon-document"></i> 报告签发单</el-divider>
    </div>
    <el-form size="large" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="status === 'audit' || status === 'taskFormDetail'|| isDisabled === 'view'"
             label-width="150px" @submit.native.prevent>
      <el-row  :gutter="15">
        <el-col :span="24">
          <el-form-item label="项目名称" prop="projectName">
            <el-input size="large" :disabled="true" v-model="inputForm.projectName" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="评估基准日" prop="assessmentDate">
            <el-input size="large" :disabled="true" v-model="inputForm.assessmentDate" clearable></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="报告文号" prop="reportNo">
            <el-input size="large" :disabled="true" v-model="inputForm.reportNo" clearable></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="项目负责人" prop="projectManager">
<!--            <SelectUserTree-->
<!--              ref="companyTree"-->
<!--              size="large"-->
<!--              :props="{-->
<!--                  value: 'id',             // ID字段名-->
<!--                  label: 'name',         // 显示名称-->
<!--                  children: 'children'    // 子级字段名-->
<!--                }"-->
<!--              :url="`/system-server/sys/user/treeUserDataAllOffice?type=2`"-->
<!--              :value="inputForm.projectManager"-->
<!--              :disabled="true"-->
<!--              :clearable="true"-->
<!--              :accordion="true"-->
<!--              @getValue="(value) => {inputForm.projectManager=value}"/>-->
			  <el-input :disabled="true" @focus="openUserDia"  v-model="inputForm.projectManagerName" placeholder="请选择项目负责人">
				  <template #suffix>
					  <el-button :disabled="true" style="background-color: white;color: #1b1e25;border-color: white;" type="primary" slot="append" icon="el-icon-search" @click="openUserDia">
					  </el-button>
				  </template>
			  </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="所属部门" prop="department">
            <el-input size="large" :disabled="true" v-model="inputForm.department" clearable></el-input>
          </el-form-item>
        </el-col>

       </el-row>

      <el-divider content-position="left"><span style="font-size: 17px;margin-left: 0px"><b>业务类型</b></span></el-divider>
      <el-row v-for="(item, index) in typeList">
		  <el-col :span="24">
      	<el-divider content-position="left"><span style="font-size: 17px;margin-left: 10px">{{item.name}}</span></el-divider>
        <vxe-table
          border="inner"
          show-overflow
          ref="table"
          class="vxe-table-element"
          :data="item.childrenList"
          style="margin-left: 5em"
          @cell-click=""
          @edit-closed=""
          :show-header="false"
          :row-config="{isHover: true,keyField: 'id'}"
          @radio-change="radioChangeEvent($event, index)"
          :radio-config="{trigger: 'row',labelField: 'name'}"
        >
          <vxe-column type="radio" align="left"></vxe-column>
<!--          <vxe-column align="left" field="name"></vxe-column>-->
        </vxe-table>
		  </el-col>
      </el-row>

      <el-row :gutter="15" style="margin-top: 40px">

        <el-col :span="12">
          <el-form-item label="是否已完善项目信息" prop="isTxtz" :rules="[{required: true, message:'请选择是否已完善项目信息', trigger:'blur'}]">
            <el-radio-group v-model="inputForm.isTxtz">
              <el-radio v-for="item in $dictUtils.getDictList('yes_no')" :label="item.value" >{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="报告电子版是否归档" prop="isBgdzdgd" :rules="[{required: true, message:'请选择报告电子版是否归档', trigger:'blur'}]">
            <el-radio-group v-model="inputForm.isBgdzdgd">
              <el-radio v-for="item in $dictUtils.getDictList('yes_no')" :label="item.value" >{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="是否需要备案" prop="isXyba" :rules="[{required: true, message:'请选择是否需要备案', trigger:'blur'}]">
            <el-radio-group v-model="inputForm.isXyba">
              <el-radio v-for="item in $dictUtils.getDictList('yes_no')" :label="item.value" >{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="是否完成备案" prop="isWcba" :rules="[{required: true, message:'请选择是否完成备案', trigger:'blur'}]">
            <el-radio-group v-model="inputForm.isWcba">
              <el-radio v-for="item in $dictUtils.getDictList('yes_no')" :label="item.value" >{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
<!--        评估报告-->
          <el-col :span="12" v-if="inputForm.reportType === '1'">
            <el-form-item label="评估报告(份)" prop="assessmentReport" :rules="[{required: true, message:'请输入评估报告（份）', trigger:'blur'}]">
              <el-input size="large" v-model="inputForm.assessmentReport" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="inputForm.reportType === '1'">
            <el-form-item label="评估说明(份)" prop="assessmentExplain" :rules="[{required: true, message:'请输入评估说明（份）', trigger:'blur'}]">
              <el-input size="large" v-model="inputForm.assessmentExplain" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="inputForm.reportType === '1'">
            <el-form-item label="评估明细表(份)" prop="assessmentDetail" :rules="[{required: true, message:'请输入评估明细表（份）', trigger:'blur'}]">
              <el-input size="large" v-model="inputForm.assessmentDetail" clearable></el-input>
            </el-form-item>
          </el-col>
<!--        咨询报告-->
          <el-col :span="12" v-if="inputForm.reportType === '2'">
            <el-form-item label="咨询报告(份)" prop="consultingReport" :rules="[{required: true, message:'请输入咨询报告（份）', trigger:'blur'}]">
              <el-input size="large" v-model="inputForm.consultingReport" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="inputForm.reportType === '2'">
            <el-form-item label="评估说明(份)" prop="assessmentExplain" :rules="[]">
              <el-input size="large" v-model="inputForm.assessmentExplain" clearable></el-input>
            </el-form-item>
          </el-col>
        <el-col :span="12">
          <el-form-item label="用印类型" prop="sealType" :rules="[{required: true, message:'请输入用印类型', trigger:'blur'}]">
            <el-input size="large" v-model="inputForm.sealType" clearable></el-input>
          </el-form-item>
        </el-col>

      </el-row>

    </el-form>
	  <user-select ref="userSelect2" @doSubmit="selectUser"></user-select>

  </div>
</template>

<script>
  import SelectUserTree from '@/views/utils/treeUserSelect'
  import ProofreadIssuedService from '@/api/sys/ProofreadIssuedService'
  import ProgramProjectListInfoService from '@/api/program/ProgramProjectListInfoService'
  import ProgramServiceTypeService from '@/api/program/ProgramServiceTypeService'
  import UserSelect from '@/views/utils/UserTreeSelect'

  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: '',
          projectId: '',
          projectName: '',
          assessmentDate: '',
          reportNo: '',
          projectManager: '',
          projectManagerName: '',
          department: '',
          isTxtz: '',
          isBgdzdgd: '',
          isXyba: '',
          isWcba: '',
          assessmentReport: '',
          assessmentExplain: '',
          assessmentDetail: '',
          consultingReport: '',
          sealType: '',
          status: '',
          agreeTime: '',
          agreeUserId: '',
          reportType: '',
          serviceType: ''
        },
        keyWatch: '',
        yesOrNo: [
          {value: 0, label: '否'},
          {value: 1, label: '是'}
        ],
        typeList: [],
        tabName: '',
        chooseTableIndex: '',
        isDisabled: ''
      }
    },
    proofreadIssuedService: null,
    programProjectListInfoService: null,
    programServiceTypeService: null,
    created () {
      this.programServiceTypeService = new ProgramServiceTypeService()
      this.proofreadIssuedService = new ProofreadIssuedService()
      this.programProjectListInfoService = new ProgramProjectListInfoService()
      this.proofreadIssuedService.findProjectInfoById(this.businessId).then((data) => {
        this.inputForm = this.recover(this.inputForm, data)
        this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
      })
      // this.getTypeList() // 获取业务类型数据
    },
    computed: {
      bus: {
        get () {
          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()
            })
          }
        }
      },
      'loading': {
        handler (newVal) {
          this.$emit('changeLoading', newVal)
        }
      }
    },
    components: {
      SelectUserTree,
		UserSelect
    },
    methods: {
      getKeyWatch (keyWatch) {
        this.keyWatch = keyWatch
      },
      init (method, id, tabName) {
        this.tabName = tabName
        this.method = method
        if (method === 'view') {
          this.isDisabled = 'view'
        }
        this.inputForm = {
          id: '',
          projectId: '',
          projectName: '',
          assessmentDate: '',
          reportNo: '',
          projectManager: '',
          projectManagerName: '',
          department: '',
          isTxtz: '',
          isBgdzdgd: '',
          isXyba: '',
          isWcba: '',
          assessmentReport: '',
          assessmentExplain: '',
          assessmentDetail: '',
          consultingReport: '',
          sealType: '',
          status: '',
          agreeTime: '',
          agreeUserId: '',
          reportType: '',
          serviceType: ''
        }
        this.inputForm.projectId = id
        this.visible = true
        this.loading = false
        // this.getTypeList()  // 获取业务类型数据
        this.$nextTick(() => {
          this.loading = true
          this.programServiceTypeService.getList().then((data) => {
            this.typeList = data
            this.proofreadIssuedService.findById(this.inputForm.projectId).then((data) => {
              if (!this.commonJS.isEmpty(data.id)) {
                this.$refs.inputForm.resetFields()
                this.inputForm = this.recover(this.inputForm, data)
                this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
                this.chooseRow() // 选中行
                this.loading = false
              } else {
                this.proofreadIssuedService.findProjectInfoById(this.inputForm.projectId).then((data) => {
                  this.inputForm = this.recover(this.inputForm, data)
                  this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
                  this.chooseRow() // 选中行
                  this.loading = false
                })
              }
            })
          })
        })
      },
      // 获取业务类型数据
      getTypeList () {
        this.programServiceTypeService.getList().then((data) => {
          this.typeList = data
        })
      },
      reapplyForm (callback) {
        this.loading = true
        this.proofreadIssuedService.findById(this.inputForm.id).then((data) => {
          if (data.status !== '4') { // 审核状态不是“驳回”，就弹出提示
            this.loading = false
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
          } else {
            this.startFormTrue(callback)
          }
        })
      },
      startForm (callback) {
        this.loading = true
        if (this.commonJS.isNotEmpty(this.inputForm.id)) {
          this.proofreadIssuedService.findById(this.inputForm.id).then((data) => {
            if (this.commonJS.isNotEmpty(data.status) && data.status !== '0' && data.status !== '1' && data.status !== '3') { // 审核状态不是“未发起”或“暂存”或“撤回”，就弹出提示
              this.loading = false
              this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
              throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            } else {
              this.startFormTrue(callback)
            }
          })
        } else {
          this.startFormTrue(callback)
        }
      },
      saveForm (callback) {
        this.loading = true
        this.inputForm.status = '1'
        this.proofreadIssuedService.save(this.inputForm).then((data) => {
          callback(data.businessTable, data.businessId, this.inputForm)
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      },
      startFormTrue (callback) {
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            this.inputForm.status = '2'
            this.proofreadIssuedService.save(this.inputForm).then((data) => {
              this.inputForm.id = data.businessId
              callback(data.businessTable, data.businessId, this.inputForm)
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          } else {
            this.loading = false
          }
        })
      },
      async agreeForm (callback) {
        this.loading = true
        await this.proofreadIssuedService.findById(this.inputForm.id).then((data) => {
          if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
            this.loading = false
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            throw new Error()
          } else {
            this.$refs['inputForm'].validate((valid) => {
              if (valid) {
                this.loading = true
                this.inputForm.status = '5'
                this.inputForm.agreeTime = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
                let userId = this.$store.state.user.id
                this.inputForm.agreeUserId = userId
                this.proofreadIssuedService.save(this.inputForm).then((data) => {
                  callback(data.businessTable, data.businessId, this.inputForm)
                  this.loading = false
                }).catch(() => {
                  this.loading = false
                })
              } else {
                this.loading = false
              }
            })
          }
        })
      },
      async updateStatusById (type, callback) {
        this.loading = true
        if (type === 'reject' || type === 'reback') {
          this.proofreadIssuedService.findById(this.inputForm.id).then((data) => {
            if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
              this.loading = false
              this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
              throw new Error()
            } else {
              // if (type === 'agree') {
              //   // 同意
              //   this.inputForm.status = '5'
              // }
              if (type === 'reject') {
                // 驳回
                this.inputForm.status = '4'
                // this.proofreadIssuedService.updateStatus(this.inputForm)
              }
              if (type === 'reback') {
                // 撤回
                this.inputForm.status = '3'
                // this.proofreadIssuedService.updateStatus(this.inputForm)
              }
              if (type === 'reject' || type === 'reback') {
                let param = {status: this.inputForm.status, id: this.inputForm.id}
                this.proofreadIssuedService.updateStatus(param).then(() => {
                  this.loading = false
                  callback()
                })
              }
            }
          })
        } else if (type === 'hold') {
          this.proofreadIssuedService.findById(this.inputForm.id).then((data) => {
            if (data.status !== '4') { // status的值不等于“驳回”就弹出提示
              this.loading = false
              this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
              throw new Error()
            } else {
              // 终止
              let param = {status: '1', id: this.inputForm.id}
              this.proofreadIssuedService.updateStatus(param).then(() => {
                this.loading = false
                callback()
              })
            }
          })
        }
      },
      // async updateStatusById (type) {
      //   await this.proofreadIssuedService.findById(this.inputForm.id).then(({data}) => {
      //     if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
      //       this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
      //       throw new Error()
      //     } else {
      //       if (type === 'reject') {
      //         // 驳回
      //         this.inputForm.status = '4'
      //         this.proofreadIssuedService.updateStatus(this.inputForm)
      //       }
      //       if (type === 'reback') {
      //         // 撤回
      //         this.inputForm.status = '3'
      //         this.proofreadIssuedService.updateStatus(this.inputForm)
      //       }
      //     }
      //   })
      // },
      close () {
        this.inputForm = {
          id: '',
          projectId: '',
          projectName: '',
          assessmentDate: '',
          reportNo: '',
          projectManager: '',
          department: '',
          isTxtz: '',
          isBgdzdgd: '',
          isXyba: '',
          isWcba: '',
          assessmentReport: '',
          assessmentExplain: '',
          assessmentDetail: '',
          consultingReport: '',
          sealType: '',
          status: '',
          agreeTime: '',
          agreeUserId: '',
          reportType: '',
          serviceType: ''
        }
        this.chooseTableIndex = ''
        this.typeList = []
        this.$refs.inputForm.resetFields()
        this.visible = false
      },
      // 下载报告签发单
      downloadReportAusstellungTpl () {
        // this.$utils.downloadExcel('/sys/project/import/template')
        this.loading = true
        this.programProjectListInfoService.downloadReportAusstellungTpl(this.inputForm.projectId).then((res) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadWord(res, '报告签发单')
          this.loading = false
        }).catch(function (err) {
          this.loading = false
          if (err.response) {
            console.log(err.response)
          }
        })
      },
      // 业务类别表格值改变事件
      radioChangeEvent (event, tableIndex) {
        if (this.status === 'audit' || this.status === 'taskFormDetail' || this.isDisabled === 'view') {  // 数据审核页面或详情页面  不允许修改数据时
          if (this.commonJS.isNotEmpty(this.chooseTableIndex)) { // chooseTableIndex有值，说明数据有默认值
            if (tableIndex === this.chooseTableIndex) { // 选中行是默认数据所属的表，不允许切换
              this.$refs.table[tableIndex].setRadioRow(event.oldValue) // 将表中的选择重新赋值上一个选择，达到未切换的目的
            } else {  // 选中行不是默认数据所属的表，不允许切换
              this.$refs.table[tableIndex].clearRadioRow() // 清空表中的选项，达到未切换数据的目的
            }
          } else {  // chooseTableIndex没有值，说明数据没有默认值，清空表中的选项
            this.$refs.table[tableIndex].clearRadioRow()
          }
        } else {  // 允许修改数据时
          // 清除其他表格的选择
          this.typeList.forEach((item, index) => {
            if (index !== tableIndex) {
              this.$refs.table[index].clearRadioRow()
            }
          })
          // 绑定表格的选择
          this.inputForm.serviceType = event.row.id
        }
      },
      // 单选框是否禁用
      // tableCheckMethod () {
      //   console.log('禁用')
      //   if (this.status === 'audit' || this.status === 'taskFormDetail') {
      //     return false
      //   }
      //   return true
      // },
      chooseRow () {
        if (this.commonJS.isNotEmpty(this.inputForm.serviceType)) {
          if (this.commonJS.isNotEmpty(this.typeList)) {
            this.typeList.forEach((item, index) => {   // 遍历出表格（A类、B类等表格）
              if (this.commonJS.isNotEmpty(item.childrenList)) {  // 每个表格中的数据遍历出来（A类表格中的数据、B类表格中的数据等等...）
                item.childrenList.forEach((child) => {
                  if (child.id === this.inputForm.serviceType) { // 如果表格中的数据等于查询到的业务类型，说明要将这条数据选中
                    this.$refs.table[index].setRadioRow(child) // 将数据改为选中状态
                    this.chooseTableIndex = index // 获取选中数据属于哪个表格
                  }
                })
              }
            })
          }
        }
      },
      // 关闭父页面时调用此方法
      closeThis () {
        this.close()
      },
		openUserDia(){
			this.$refs.userSelect2.init()
		},
		selectUser(user){
			console.log(user[0].name)
			this.inputForm.projectManagerName=user[0].name
			this.inputForm.projectManager=user[0].id
		},
    }
  }
</script>
<style scoped>
  /deep/ .w-e-text-container {
    z-index: 1 !important;
  }
  /deep/ .wtext {
    height: 200px
  }
  .el-divider__text {
    font-size: 16px;
    font-weight: bold;
  }
</style>
