<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
	  draggable
      width="1400px"
      height="500px"
      @close="close"
      append-to-body
      v-model="visible">
    <el-row>
      <el-col :span="24">
        <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="status === 'audit' || status === 'taskFormDetail'|| method ==='view'"
                     label-width="135px" @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="projectName"
                                :rules="[
                                {required: true, message:'项目名称不能为空', trigger:'blur'}
                   ]">
                    <el-input :disabled="true" v-model="inputForm.projectName" placeholder="请填写项目名称" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目编号" prop="projectNumber"
                                :rules="[
                   ]">
                    <el-input :disabled="true" v-model="inputForm.projectNumber" placeholder="请填写项目编号" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="创建人" prop="createName"
                                :rules="[
                   ]">
                    <el-input :disabled="true" v-model="inputForm.createName" placeholder="请填写创建人" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="创建时间" prop="createTime"
                                :rules="[
                   ]">
                    <el-input :disabled="true" v-model="inputForm.createTime" placeholder="请填写创建时间" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
			<el-divider content-position="left"><i class="el-icon-document"></i> 项目计划列表
				<el-button size="default" style="margin-left: 20px" type="primary" :disabled = "method === 'view'" @click="insertEvent()" plain>
					新增
				</el-button>
				<el-button size="default" style="margin-left: 20px" type="primary" :disabled = "method === 'view'" @click="exportPlan()" plain>
					导出
				</el-button>
				<a v-if="commonJS.isNotEmpty(inputForm.planStartDate) && commonJS.isNotEmpty(inputForm.planEndDate)" style="margin-left: 1em;font-size: 14px">项目起始时间:{{inputForm.planStartDate}} - {{inputForm.planEndDate}}</a>
			</el-divider>
			<el-row  :gutter="15">
				<el-col :span="24">
					<vxe-table
						border
						show-overflow
						show-footer
						:column-config="{resizable: true}"
						ref="detailTable"
						:key="detailkey"
						class="vxe-table-element"
						:data="inputForm.planDetailsList"
						style=""
						highlight-current-row
						:edit-config="{trigger: 'click', mode: 'row', showStatus: true, autoClear: true, icon:'_'}"
					>
						<vxe-table-column type="seq" width="60" title="序号"></vxe-table-column>
						<vxe-table-column field="taskPhase" title="任务阶段" :edit-render="{}" show-overflow="title" :rules="[{required: true, message:'请输入任务阶段', trigger:'blur'}]">
							<template v-slot:edit="scope">
								<el-autocomplete
									value-key="taskPhase"
									class="inline-input"
									v-model="scope.row.taskPhase"
									:fetch-suggestions="querySearch"
									:trigger-on-focus="false"
									clearable
									placeholder="请输入内容"
									:popper-append-to-body="false"
									:popper-class="vxetableignoreclear"
								></el-autocomplete>
							</template>
						</vxe-table-column>
						<vxe-table-column field="planStartDate" title="计划开始时间" :edit-render="{}" show-overflow="title">
							<template v-slot:edit="scope">
								<el-date-picker
									v-model="scope.row.planStartDate"
									type="date"
									value-format="YYYY-MM-DD"
									placeholder="选择计划开始时间"
									style="width:100%"
									placement="bottom-start"
									clearable>
								</el-date-picker>
							</template>
						</vxe-table-column>
						<vxe-table-column field="planEndDate" title="计划结束时间" :edit-render="{}" show-overflow="title">
							<template v-slot:edit="scope">
								<el-date-picker
									v-model="scope.row.planEndDate"
									type="date"
									value-format="YYYY-MM-DD"
									placeholder="选择计划结束时间"
									style="width:100%"
									placement="bottom-start"
									clearable>
								</el-date-picker>
							</template>
						</vxe-table-column>
						<vxe-table-column field="warnName" title="提醒人" :edit-render="{}" show-overflow="title">
							<template v-slot:edit="scope">
								<el-input v-model="scope.row.warnName" @focus="userPullListForm1(scope.$rowIndex)"></el-input>
							</template>
						</vxe-table-column>
						<vxe-table-column field="achieverName" title="完成人" :edit-render="{}" show-overflow="title">
							<template v-slot:edit="scope">
								<el-input v-model="scope.row.achieverName" @focus="userPullListForm(scope.$rowIndex)"></el-input>
							</template>
						</vxe-table-column>
						<vxe-table-column title="操作" width="100">
							<template v-slot="scope">
								<el-button size="default" type="danger" :disabled = "method === 'view'" @click="removeEvent(scope.row,scope.$rowIndex)"  >删除</el-button>
							</template>
						</vxe-table-column>
					</vxe-table>
				</el-col>
			</el-row>
        </el-form>
		  <UpLoadComponent ref="uploadComponent"></UpLoadComponent>
      </el-col>
    </el-row>
		<template #footer>
			<span class="dialog-footer">
			  <el-button @click="close()" icon="el-icon-circle-close">关闭</el-button>
			  <el-button v-if="method === 'edit' || method === 'add'" type="primary" icon="el-icon-circle-check" @click="save()">确定</el-button>
			</span>
		</template>
    </el-dialog>
	  <UserPullForm ref="userPullForm" @getProgramForUser="getProgramForUser"></UserPullForm>
	  <UserPullFormPlan ref="userPullFormPlan" @getProgramForUser="getProgramForUser1"></UserPullFormPlan>
  </div>




</template>

<script>
  import UpLoadComponent from '@/views/common/UpLoadComponent'
  import projectRecordsService from '@/api/cw/projectRecords/ProjectRecordsService'
  import UserPullForm from '@/views/finance/invoice/UserPullForm'
  import UserPullFormPlan from '@/views/finance/invoice/UserPullFormPlan'
  export default {
	  props: {
		  businessId: {
			  type: String,
			  default: ''
		  },
		  formReadOnly: {
			  type: Boolean,
			  default: false
		  },
		  status: {
			  type: String,
			  default: ''
		  }
	  },
	  data() {
		  return {
			  showChildDialog: false,
			  typeVisible: false,
			  title: '',
			  method: '',
			  loading: false,
			  inputForm: {
				  id: '',
				  createDate: '',
				  createName: '',
				  createTime: '',
				  remarks: '',
				  projectNumber: '',
				  projectName: '',
				  planFileList: [],
				  planStartDate: '',
				  planEndDate: '',
				  planDetailsList: [],
			  },
			  keyWatch: '',
			  detailkey: '',
			  visible: false,
			  restaurants: [],
			  tableIndex:0,
			  vxetableignoreclear:'vxe-table--ignore-clear'
		  }
	  },

	  created() {

	  },
	  computed: {
		  bus: {
			  get() {
				  this.$refs.uploadComponent.setDividerName('项目计划附件信息', false)
				  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()
					  })
				  }
			  }
		  }
	  },
	  mounted() {
		  this.loadAll();
	  },
	  components: {
		  UpLoadComponent,
		  UserPullForm,
		  UserPullFormPlan
	  },
	  methods: {
		  getKeyWatch(keyWatch) {
			  this.keyWatch = keyWatch
		  },
		  forUpdate() {
			  this.$forceUpdate()
		  },
		  init(method, id) {
			  if (method === 'add') {
				  this.title = '添加项目计划信息'
			  } else if (method === 'edit'){
				  this.title = '修改项目计划信息'
			  }else if (method === 'view'){
				  this.title = '查看项目计划信息'
			  }
			  this.visible = true
			  this.method = method
			  this.inputForm = {
				  id: '',
				  createName: '',
				  createTime: '',
				  remarks: '',
				  projectNumber: '',
				  projectName: '',
				  planFileList: [],
				  planStartDate: '',
				  planEndDate: '',
				  planDetailsList: []
			  }
			  this.inputForm.id = id
			  this.loading = false
			  this.$nextTick(() => {
				  this.$refs.inputForm.resetFields()
				  this.loading = true
				  projectRecordsService.queryPlanById(this.inputForm.id).then((data) => {
				  	console.log('data',data)
					  this.$refs.uploadComponent.clearUpload()
					  this.inputForm = this.recover(this.inputForm, data)
					  this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
					  this.inputForm.planStartDate = data.projectStartTime
					  this.inputForm.planEndDate = data.projectEndTime
					  // if (this.commonJS.isEmpty(data.planStartDate)){
						//   this.inputForm.planStartDate = this.moment(data.planStartDate).format('YYYY-MM-DD')
					  // }
					  // if (this.commonJS.isEmpty(data.planEndDate)){
						//   this.inputForm.planEndDate = this.moment(data.planEndDate).format('YYYY-MM-DD')
					  // }
						console.log('this.inputForm.planStartDate',this.inputForm.planStartDate)
					  if (this.commonJS.isEmpty(this.inputForm.planDetailsList)) {
						  this.inputForm.planDetailsList = []
						  let phase = this.$dictUtils.getDictList('cw_project_plan_phase')
						  console.log('phase',phase)
						  phase.forEach((item) => {
							  console.log('item', item)
							  let a = {
								  taskPhase: item.label,
								  planStartDate: '',
								  planEndDate: '',
								  warnName: this.$store.state.user.name,
								  warnUser:this.$store.state.user.id,
								  achiever:this.$store.state.user.id,
								  achieverName: this.$store.state.user.name,
							  }
							  this.$refs.detailTable.insertAt(a)
							  this.inputForm.planDetailsList.push(a)
							  this.detailkey = Math.random()
						  })
						  var li = this.inputForm.planDetailsList.length - 1
						  console.log('this.inputForm.planStartDate',this.inputForm.planDetailsList)
						  if (this.commonJS.isNotEmpty(this.inputForm.planStartDate)) {
							  this.inputForm.planDetailsList[0].planStartDate = this.inputForm.planStartDate
						  }
						  if (this.commonJS.isNotEmpty(this.inputForm.planEndDate)) {
							  this.inputForm.planDetailsList[li].planEndDate = this.inputForm.planEndDate
						  }
					  }
					  this.$refs.uploadComponent.newUpload(this.method, this.inputForm.planFileList, 'cw_project_plan', null, '项目计划附件信息', null, null, false)

					  this.loading = false
				  })
			  })
		  },
		  // 表单提交
		  save() {
			  this.$refs['inputForm'].validate((valid) => {
				  if (valid) {
					  this.loading = true
					  if (this.commonJS.isEmpty(this.inputForm.planDetailsList)) {
						  this.loading = false
						  this.$message.error('至少输入一条项目计划')
						  throw new Error('至少输入一条项目计划')
					  }else {
					  	let begindate = this.inputForm.planDetailsList[0].planStartDate
					  	let planLength = this.inputForm.planDetailsList.length -1
						  let endDate = this.inputForm.planDetailsList[planLength].planEndDate
						  this.inputForm.planStartDate = this.moment(begindate).format('YYYY-MM-DD HH:mm:ss')
						  this.inputForm.planEndDate = this.moment(endDate).format('YYYY-MM-DD HH:mm:ss')
						  for (let i = 0; i < this.inputForm.planDetailsList.length; i++) {
						  	if (this.commonJS.isEmpty(this.inputForm.planDetailsList[i].planEndDate)){
								this.loading = false
								this.$message.error('第'+(i+1)+'行计划结束时间未选择')
								throw new Error('第'+(i+1)+'行计划结束时间未选择')
							}
							  if (this.commonJS.isEmpty(this.inputForm.planDetailsList[i].planStartDate)){
								  this.loading = false
								  this.$message.error('第'+(i+1)+'行计划开始时间未选择')
								  throw new Error('第'+(i+1)+'行计划开始时间未选择')
							  }
							  //横向比较开始时间和结束时间
							  if (this.inputForm.planDetailsList[i].planEndDate < this.inputForm.planDetailsList[i].planStartDate){
								  this.loading = false
								  this.$message.error('第'+(i+1)+'行计划结束时间不能小于计划开始时间')
								  throw new Error('第'+(i+1)+'行计划结束时间不能小于计划开始时间')
							  }
							  //纵向比较开始时间和结束时间
							  if (this.inputForm.planDetailsList[i].planStartDate<begindate){
								  this.loading = false
								  this.$message.error('第'+(i+1)+'行计划开始时间不能小于第一行的计划开始时间')
								  throw new Error('第'+(i+1)+'行计划开始时间不能小于第一行的计划开始时间')
							  }
							  if (this.inputForm.planDetailsList[i].planEndDate>endDate){
								  this.loading = false
								  this.$message.error('第'+(i+1)+'行计划结束时间不能大于最后一行的计划结束时间')
								  throw new Error('第'+(i+1)+'行计划结束时间不能大于最后一行的计划结束时间')
							  }
						  }
					  }
					  console.log('this.inputForm',this.inputForm)
					  this.inputForm.planFileList = this.$refs.uploadComponent.getDataList()
					  projectRecordsService.savePlanForm(this.inputForm).then((data) => {
						  this.$emit('refreshList')
						  this.loading = false
						  this.close()
					  }).catch(() => {
						  this.loading = false
					  })
				  }
			  })
		  },
		  close() {
			  this.inputForm = {
				  id: '',
				  createName: '',
				  createTime: '',
				  remarks: '',
				  projectNumber: '',
				  projectName: '',
				  planFileList: [],
				  planStartDate: '',
				  planEndDate: '',
				  planDetailsList: []
			  }
			  this.$refs.uploadComponent.clearUpload()
			  this.$refs.inputForm.resetFields()
			  this.visible = false
		  },
		  // 新增
		  // eslint-disable-next-line no-dupe-keys
		  async insertEvent() {
			  let d = {
				  taskPhase: '',
				  planStartDate: '',
				  planEndDate: '',
				  warnUser: '',
				  achiever: '',
			  }
			  if (this.commonJS.isEmpty(this.inputForm.planDetailsList)) {
				  this.inputForm.planDetailsList = []
			  }

			  console.log('this.inputForm.planDetailsList', this.inputForm.planDetailsList)
			  this.$refs.detailTable.insertAt(d)
			  this.inputForm.planDetailsList.push(d)
			  this.detailkey = Math.random()

		  },
		  // 删除
		  removeEvent(row, rowIndex) {
			  this.$refs.detailTable.remove(row)
			  this.inputForm.planDetailsList.splice(rowIndex, 1)
		  },
		  querySearch(queryString, cb) {
		  	console.log('queryString',queryString)
			  const restaurants = this.restaurants
			  let results = queryString
				  ? restaurants.filter(
					  this.createFilter(queryString)
				  )
				  : restaurants
			  console.log('results',results)
			  cb(results.map(restaurant => ({ taskPhase: restaurant.value })))
		  },
		  createFilter(queryString) {
			  return (taskPhase) => {
				  return taskPhase.value.toUpperCase().startsWith(queryString.toUpperCase());
			  };
		  },
		  loadAll() {
				 projectRecordsService.getTaskPhase().then((data)=>{
					this.restaurants=data
			  })

		  },
		  // handleSubmit(item) {
			//
		  // },
		  // 自定义服务端导出
		  exportPlan() {
		  	let optionName = this.inputForm.projectName+"项目计划.xls"
			  // 传给服务端的参数
			  const params = {
				  id: this.inputForm.id,
				  mode:'all'
			  }
			  return projectRecordsService.exportPlan(params).then((res) => {
				  // 将二进制流文件写入excel表，以下为重要步骤
				  this.$utils.downloadExcel(res,  optionName)
			  }).catch(function (err) {
				  if (err.response) {
					  console.log(err.response)
				  }
			  })
		  },
		  userPullListForm (rowIndex) {
			  this.indexRow = rowIndex
			  this.$refs.userPullForm.init()
		  },
		  getProgramForUser (rows) {
			  this.inputForm.planDetailsList[this.indexRow].achiever = rows[0].id
			  this.inputForm.planDetailsList[this.indexRow].achieverName = rows[0].name
			  this.indexRow = ''
			  this.$forceUpdate()
		  },
		  userPullListForm1 (rowIndex) {
			  this.indexRow = rowIndex
			  this.$refs.userPullFormPlan.init(this.inputForm.id)
		  },
		  getProgramForUser1 (rows) {
			  this.inputForm.planDetailsList[this.indexRow].warnUser = rows[0].id
			  this.inputForm.planDetailsList[this.indexRow].warnName = rows[0].name
			  this.indexRow = ''
			  this.$forceUpdate()
		  },
	  }

  }
</script>
<style scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
</style>
<style>
  .vxe-select--panel {
    z-index: 9997 !important
  }
</style>
