<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
	  <el-dialog
		  :title="title"
		  :close-on-click-modal="false"
		  draggable
		  width="1200px"
		  @close="close"
		  append-to-body
		  @keyup.enter.native="doSubmit"
		  v-model="visible">
    <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="status === 'audit' || status === 'taskFormDetail' || method === 'view'"
             label-width="160px" @submit.native.prevent>
		<el-divider content-position="left"><i class="el-icon-document"></i>
			签章项目信息
			<el-button style="margin-left: 20px" type="primary" :disabled="status === 'audit' || status === 'taskFormDetail'" @click="insertEvent()"  plain>
				新增
			</el-button>
		</el-divider>
		<el-row  :gutter="15">
			<el-col :span="24">
				<vxe-table
					border
					show-overflow
					ref="baseTable"
					:key="baseKey"
					class="vxe-table-element"
					:data="inputForm.projectList"
					style="margin-left: 5em"
					@cell-click=""
					@edit-closed=""
					keep-source
					highlight-current-row
					:edit-config="{trigger: 'click', mode: 'cell', showStatus: true, autoClear: true, icon: '-'}"
				>
					<vxe-table-column field="projectName" align="center" title="项目名称" :edit-render="{}" show-overflow="title">
						<template v-slot:edit="scope">
							<el-input @focus="openProgramPageForm(scope.$rowIndex)" placeholder="请填写项目名称" :readonly="true" v-model="scope.row.projectName"/>
						</template>
					</vxe-table-column>
					<vxe-table-column field="reportNo" align="center" title="报告号"></vxe-table-column>
					<vxe-table-column field="contractName" align="center" title="合同名称"></vxe-table-column>
					<vxe-table-column field="projectNumber" align="center" title="项目编号" ></vxe-table-column>
					  <vxe-table-column field="clientContactsName" title="委托方" ></vxe-table-column>
					<vxe-table-column title="操作" align="center" width="100">
						<template v-slot="scope">
							<el-button type="danger" @click="removeEvent(scope.row,scope.$rowIndex)">删除</el-button>
						</template>
					</vxe-table-column>
				</vxe-table>
			</el-col>
		</el-row>
      <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="signatureName"
                        :rules="[{required: true, message:'签章描述不能为空', trigger:'blur'}
               ]">
            <el-input  placeholder="请填写签章描述" v-model="inputForm.signatureName" clearable></el-input>
          </el-form-item>
        </el-col>
		  <el-col :span="12">
			  <el-form-item label="签章编号" prop="number"
							:rules="[
               ]">
				  <el-input :disabled="true" placeholder="签章编号自动生成" v-model="inputForm.number" clearable></el-input>
			  </el-form-item>
		  </el-col>
        <el-col :span="12">
          <el-form-item label="签章类型" prop="signatureType"
                        :rules="[
                        {required: true, message:'签章类型不能为空', trigger:'change'}
               ]">
			  <el-select v-model="inputForm.signatureType" placeholder="请选择" style="width:100%;" clearable>
				  <el-option
					  v-for="item in $dictUtils.getDictList('signature_project_report')"
					  :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="createName"
							:rules="[
               ]">
				  <el-input :disabled="true" placeholder="请填写创建人" v-model="inputForm.createName" clearable></el-input>
			  </el-form-item>
		  </el-col>
		  <el-col :span="12">
			  <el-form-item label="所属部门" prop="officeName"
							:rules="[
               ]">
				  <el-input :disabled="true" placeholder="请填写所属部门" v-model="inputForm.officeName" clearable></el-input>
			  </el-form-item>
		  </el-col>
		  <el-col :span="12">
			  <el-form-item label="创建日期" prop="createTime"
							:rules="[
               ]">
				  <el-input :disabled="true" placeholder="请填写创建日期" v-model="inputForm.createTime" clearable></el-input>
			  </el-form-item>
		  </el-col>
		  <el-col :span="24">
			  <el-form-item label="备注" prop="remarks"
							:rules="[
               ]">
				  <el-input maxlength="500"  type="textarea" placeholder="请填写备注" v-model="inputForm.remarks" show-word-limit></el-input>
			  </el-form-item>
		  </el-col>
      </el-row>



    </el-form>
    <!--        附件-->
    <UpLoadComponent ref="uploadComponent"></UpLoadComponent>
    <UpLoadComponent2 ref="uploadComponent2"></UpLoadComponent2>
	<ProgramPageForm ref="programPageForm" @getProgram="getProgram"></ProgramPageForm>
		  <template #footer>
			<span class="dialog-footer">
			  <el-button @click="close()" icon="el-icon-circle-close">关闭</el-button>
			  <el-button type="primary" v-if="method != 'view'" @click="doSubmit()" icon="el-icon-circle-check" v-noMoreClick>确定</el-button>
			</span>
		  </template>
	  </el-dialog>
  </div>
</template>

<script>
  import SignatureReportService from '@/api/cw/signatureDaily/SignatureReportService'
  import UpLoadComponent from '@/views/common/SignatureUpLoadComponent'
  import UpLoadComponent2 from '@/views/common/SignatureUpLoadComponent'
  import ProgramPageForm from "./ProgramPageForm";
  import CommonApi from '@/api/cw/common/CommonApi'
  export default {
	  props: {
		  businessId: {
			  type: String,
			  default: ''
		  },
		  formReadOnly: {
			  type: Boolean,
			  default: false
		  },
		  status: {
			  type: String,
			  default: ''
		  }
	  },
	  data() {
		  return {
			  bj1: '',
			  title: '',
			  method: '',
			  visible: false,
			  loading: false,
			  dialogFormVisible: false,
			  inputForm: {
				  id: '',
				  signatureName:'',
				  signatureType:'',
				  number:'',
				  createName:'',
				  officeName:'',
				  createTime:'',
				  remarks: '',
				  name: '',
				  status: '',
				  files: [],
				  projectList:[],
				  procInsId:'',
				  signatureFiles:[]
			  },
			  keyWatch: '',
			  programRow: '',
			  baseKey: '',
		  }
	  },
	  SignatureReportService: null,
	  commonApi: null,
	  created() {
		  this.signatureReportService = new SignatureReportService()
		  this.commonApi = new CommonApi()
	  },
	  mounted() {
	  },
	  components: {
		  UpLoadComponent,
		  UpLoadComponent2,
		  ProgramPageForm
	  },
	  computed: {
		  bus: {
			  get() {
				  this.$refs.uploadComponent.setDividerName('附件')
				  this.$refs.uploadComponent2.setDividerName('附件')
				  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()
					  })
				  }
			  }
		  },
		  'loading': {
			  handler(newVal) {
				  this.$emit('changeLoading', newVal)
				  this.$refs.uploadComponent.changeLoading(newVal)
				  this.$refs.uploadComponent2.changeLoading(newVal)
			  }
		  }
	  },
	  methods: {
		  getKeyWatch(keyWatch) {
			  this.keyWatch = keyWatch
		  },
		  init(method, id) {
			  this.importVisible = false
			  this.method = method
			  this.inputForm = {
				  id: '',
				  signatureName:'',
				  signatureType:'',
				  number:'',
				  createName:'',
				  officeName:'',
				  createTime:'',
				  remarks: '',
				  name: '',
				  status: '',
				  files: [],
				  projectList:[],
				  procInsId:'',
				  signatureFiles:[]
			  }
			  if (method === 'add') {
				  this.title = `新建日常签章`
			  } else if (method === 'edit') {
				  this.title = '修改日常签章'
			  } else if (method === 'view') {
				  this.title = '查看日常签章信息'
			  }
			  this.inputForm.id = id
			  this.visible = true
			  this.loading = false
			  this.$nextTick(() => {
				  this.$refs.inputForm.resetFields()
				  this.loading = true
				  this.signatureReportService.findById(this.inputForm.id).then((data) => {
					  this.$refs.uploadComponent.clearUpload()
					  this.$refs.uploadComponent2.clearUpload()
					  this.inputForm = this.recover(this.inputForm, data)
					  this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
					  if (this.commonJS.isEmpty(this.inputForm.createName)) {
						  this.inputForm.createName = this.$store.state.user.name
						  this.inputForm.officeName = this.$store.state.user.office.name
					  }
					  if (this.commonJS.isEmpty(this.inputForm.createTime)) {
						  this.inputForm.createTime = this.moment(new Date()).format("YYYY-MM-DD")
					  }
					  if (this.commonJS.isEmpty(this.inputForm.files) || this.inputForm.files.length === 0) {
						  this.inputForm.files = []
					  }
					  if (this.commonJS.isEmpty(this.inputForm.projectList) || this.inputForm.projectList.length === 0) {
						  this.inputForm.projectList = []
					  }
					  if (this.status === 'audit' || this.status === 'taskFormDetail') {
						  method = 'view'
					  }
					  if (this.commonJS.isEmpty(this.inputForm.signatureFiles) || this.inputForm.signatureFiles.length === 0) {
						  this.inputForm.signatureFiles = []
					  }
					  console.log('this.inputForm',this.inputForm)
					  this.$refs.uploadComponent.newUpload(method, this.inputForm.files, 'signatureReport')
					  this.$refs.uploadComponent2.newUpload(method, this.inputForm.signatureFiles, 'signatureReport')
					  this.loading = false
				  })
			  })
		  },
		  saveForm(callback) {
			  this.doSubmit('save', callback)
		  },
		  startForm(callback) {
			  this.loading = true
			  if (this.commonJS.isNotEmpty(this.inputForm.id)) {
				  this.signatureReportService.findById(this.inputForm.id).then((data) => {
					  if (data.status !== '0' && data.status !== '1' && data.status !== '3') { // 审核状态不是“未发起”或“暂存”或“撤回”，就弹出提示
						  this.loading = false
						  this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						  throw new Error()
					  } else {
						  this.doSubmit('start', callback)
					  }
				  })
			  } else {
				  this.doSubmit('start', callback)
			  }
		  },
		  async agreeForm(callback) {
			  console.log('进入方法')
			  this.loading = true
			  await  this.signatureReportService.findById(this.inputForm.id).then((data) => {
				  if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
					  this.loading = false
					  this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
					  throw new Error()
				  } else {
				  	this.inputForm.status = '2'
					  this.$refs['inputForm'].validate((valid) => {
						  if (valid) {
							  this.loading = true
							  this.inputForm.files = this.$refs.uploadComponent.getDataList()
							  if (this.commonJS.isEmpty(this.inputForm.files) || this.inputForm.files.length === 0) {
								  this.loading = false
								  this.$message.error('请上传签章附件')
								  throw new Error()
							  }
							  if (this.commonJS.isEmpty(this.inputForm.projectList) || this.inputForm.projectList.length === 0) {
								  this.loading = false
								  this.$message.error('请选择签章项目')
								  throw new Error()
							  }
							  this.commonApi.getTaskNameByProcInsId(this.inputForm.procInsId).then((data) => {
								  if (this.commonJS.isNotEmpty(data)) {
									  if (data === '办公室审批') {
										  this.inputForm.status = '5'
									  }
								  }
								  console.log('this.inputForm',this.inputForm)
								  this.signatureReportService.saveForm(this.inputForm).then((data) => {
									  if (status === 'start' || status === 'reapply') {
										  this.inputForm.title = `${this.$store.state.user.name} 发起了 ${data.number} [财务-报告签章]`
									  }
									  this.inputForm.id = data.businessId
									  console.log('data22', data)
									  callback(data.businessTable, data.businessId, this.inputForm)
									  this.loading = false
								  }).catch(() => {
									  this.loading = false
								  })
							  })
						  } else {
							  this.loading = false
						  }
					  })
				  }
			  })
		  },
		  reapplyForm(callback) {
			  this.loading = true
			  this.signatureReportService.findById(this.inputForm.id).then((data) => {
				  if (data.status !== '4') { // 审核状态不是“驳回”，就弹出提示
					  this.loading = false
					  this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
					  throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
				  } else {
					  this.doSubmit('reapply', callback)
				  }
			  })
		  },
		  // 表单提交
		  async doSubmit(status, callback) {
			  this.loading = true
			  this.$refs['inputForm'].validate((valid) => {
				  if (valid) {
					  this.loading = true
					  this.inputForm.files = this.$refs.uploadComponent.getDataList()
					  if (this.commonJS.isEmpty(this.inputForm.files) || this.inputForm.files.length === 0) {
						  this.loading = false
						  this.$message.error('请上传签章附件')
						  throw new Error()
					  }
					  if (this.commonJS.isEmpty(this.inputForm.projectList) || this.inputForm.projectList.length === 0) {
						  this.loading = false
						  this.$message.error('请选择签章项目')
						  throw new Error()
					  }

					  this.signatureReportService.saveForm(this.inputForm).then((data) => {
						  this.$refs.inputForm.resetFields()
						  this.close()
						  this.$emit('refreshDataList')
						  this.loading = false
					  }).catch(() => {
						  this.loading = false
					  })
				  } else {
					  this.loading = false
				  }
			  })
		  },
		  close() {
			  this.$refs.uploadComponent.clearUpload()
			  this.$refs.inputForm.resetFields()
			  this.inputForm = {
				  id: '',
				  signatureName:'',
				  signatureType:'',
				  number:'',
				  createName:'',
				  officeName:'',
				  createTime:'',
				  remarks: '',
				  name: '',
				  status: '',
				  files: [],
			  }
			  this.visible = false
		  },

		  async updateStatusById(type, callback) {
			  this.loading = true
			  if (await this.$refs.uploadComponent.checkProgress()) {
				  this.loading = false
				  throw new Error()
			  } else {
				  if (type === 'reject' || type === 'reback') {
					  this.signatureReportService.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'
							  }
							  if (type === 'reback') {
								  // 撤回
								  this.inputForm.status = '3'
							  }
							  if (type === 'reject' || type === 'reback') {
								  let param = {status: this.inputForm.status, id: this.inputForm.id}
								  this.signatureReportService.updateStatusById(param).then(() => {
									  this.loading = false
									  callback()
								  })
							  }
						  }
					  })
				  } else if (type === 'hold') {
					  this.signatureReportService.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.signatureReportService.updateStatusById(param).then(() => {
								  this.loading = false
								  callback()
							  })
						  }
					  })
				  }
			  }
		  },
		  insertEvent() {
			  this.$refs.baseTable.insertAt({})
			  this.inputForm.projectList.push({})
			  this.baseKey = Math.random()
		  },
		  // 删除
		  removeEvent(row, rowIndex) {
			  this.$refs.baseTable.remove(row)
			  this.inputForm.projectList.splice(rowIndex, 1)
		  },
		  openProgramPageForm(rowIndex) {
			  this.$refs.programPageForm.init()
			  this.programRow = rowIndex
		  },
		  getProgram(rows) {
			  rows.forEach((item, index) => {
				  if (index === 0) {
					  let r = this.inputForm.projectList[this.programRow]
					  r.projectName = item.projectName
					  r.contractName = item.contractName
					  r.projectNumber = item.projectNumber
					  r.id = item.id
					  r.reportNo = item.reportNo
					  r.clientContactsName = item.clientContactsName
					  this.inputForm.projectList[this.programRow] = r
				  } else {
					  let r = {
						  projectName: item.projectName,
						  contractName: item.contractName,
						  projectNumber: item.projectNumber,
						  id: item.id,
						  reportNo: item.reportNo,
						  clientContactsName:item.clientContactsName,
					  }
					  this.$refs.baseTable.insertAt(r)
					  this.inputForm.projectList.push(r)
					  this.baseKey = Math.random()
				  }
			  })
			  this.$forceUpdate()
			  this.programRow = ''
		  },

    }
  }
</script>
<style scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
  /deep/ .vxe-footer--row .vxe-footer--column:nth-child(1) .vxe-cell--item {
	  font-weight:700;
  }
</style>
