<template>
  <div v-loading="loading">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
      <el-form-item label="任务名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入任务名称"/>
      </el-form-item>
      <el-form-item label="任务时间" prop="taskDate">
        <el-date-picker
          v-model="ruleForm.taskDate"
          :picker-options="pickerOptions"
          class="filter-item"
          type="daterange"
          format="yyyy年MM月dd日"
          value-format="yyyy-MM-dd"
          align="left"
          unlink-panels
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        />
      </el-form-item>
      <el-form-item label="任务内容" prop="content">
        <el-input v-model="ruleForm.content" type="textarea" autosize placeholder="请输入任务内容"/>
      </el-form-item>
      <el-form-item label="任务类型" prop="taskTypeId">
         <el-select v-model="ruleForm.taskTypeId" clearable placeholder="请选择任务类型">
          <el-option
            v-for="item in taskType"
            :key="item.id"
            :label="item.label"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="taskStateId">
         <el-select v-model="ruleForm.taskStateId" clearable placeholder="请选择任务状态">
          <el-option
            v-for="item in taskState"
            :key="item.id"
            :label="item.label"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="任务部门" prop="depid">
           <el-cascader
              v-model="ruleForm.depid"
              :options="depData"
              :props="props"
               @change="handleTaskMan"
              placeholder="请选择任务部门"
              class="form_select"
              clearable
              filterable
              change-on-select
            />
      </el-form-item>
      <el-form-item label="任务人" prop="person">
        <el-select v-model="ruleForm.person" clearable placeholder="请选择任务人" @change='handleChange'>
          <el-option
            v-for="item in taskMan"
            :key="item.F_UserId"
            :label="item.F_UserName"
            :value="item.F_UserId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="目标金额" prop="targetAmount">
          <el-input :maxlength="10" v-model.number="ruleForm.targetAmount" placeholder="请输入目标金额"/>
      </el-form-item>
      <el-form-item label="当前金额" prop="currentAmount">
          <el-input :maxlength="10" v-model="ruleForm.currentAmount" placeholder="请输入当前金额"/>
      </el-form-item>
      <el-form-item label="提醒时间" prop="reminderTime">
        <el-date-picker
          v-model="ruleForm.reminderTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetime"
          placeholder="请选择提醒时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {getDepartmentTreeList} from '@/api/commonAPI';
import { addTask,editTask,getTask,getTaskmanData} from '@/api/taskManagement/taskManagement'
import { filterContent,pickerOptions } from '@/utils'

export default {
  name: 'AddOrEdit',
  props: {
    rowid: {
      type: String,
      default: ''
    },
    parentId: {
      type: Number,
      default: 0
    },
    layerid: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      ruleForm: {
        id: '',
        taskDate: [],//任务时间
        name: '',
        content: '',
        person: '',//任务人
        targetAmount: '',//目标金额
        currentAmount: '',//当前金额
        taskTypeId: '',//任务类型id
        depid: [],//任务部门id
        taskStateId: '',//任务状态
        reminderTime: '',//提醒时间
      },
      taskMan:[],//任务人数据
      rules: {
        name: [{
          required: true,
          message: '请输入任务名称!',
          trigger: 'blur'
        }],
        content: [{
          required: true,
          message: '请输入任务内容!',
          trigger: 'blur'
        }],
        taskDate: [{
          required: true,
          message: '请选择任务时间!',
          trigger: 'blur'
        }],
        taskTypeId: [{
          required: true,
          message: '请选择任务类型!',
          trigger: 'change'
        }],
        depid: [{
          required: true,
          message: '请选择任务部门!',
          trigger: 'change'
        }],
        taskStateId: [{
          required: true,
          message: '请选择任务状态!',
          trigger: 'change'
        }],
        targetAmount: [{
          required: true,
          message: '请输入目标金额!',
        },
        { type: 'number', message: '目标金额必须为数字'}],
        currentAmount: [{ 
          required: false,
          validator:(rule,value,callback)=>{
          if(value != ""){
                  if(value.match(/^\d*(\.?\d{0,2})/g)[0] == false){
                      callback(new Error("请填写数字"));
                  }else{
                      callback();
                  }
              }else{
                  callback();
              }

          },
          }],
      },
      taskType:[
        {
          id:0,
          label:'日'
        },
        {
          id:1,
          label:'周'
        },
        {
          id:2,
          label:'月'
        },
      ],
      taskState:[
        {
          id:0,
          label:'开始'
        },
        {
          id:1,
          label:'暂停'
        },
        {
          id:2,
          label:'终止'
        },
      ],
      props: {
        // 自定义部门下拉数据的key值
        value: "id",
        label: "text",
        children:'children'
      },
      depData:[],//部门数据
      pickerOptions,//日期数据
      loading: false,
      
    }
  },
  created() {
    this.getDepartment()
    if (this.rowid) {
      this.ruleForm.id = this.rowid
      this.getDetail(parseInt(this.rowid))
    }
  },
  methods: {
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.loading = true
          const datas = {
            F_ID: this.ruleForm.id,
            F_Name:this.ruleForm.name,
            F_Content:this.ruleForm.content,
            F_StartTime:this.ruleForm.taskDate&&this.ruleForm.taskDate[0],
            F_EndTime:this.ruleForm.taskDate&&this.ruleForm.taskDate[1],
            F_Type:this.ruleForm.taskTypeId,
            F_Deptid:this.ruleForm.depid.toString(),
            F_Tasker:this.ruleForm.person,
            F_Money:this.ruleForm.targetAmount,
            F_Currentamount:this.ruleForm.currentAmount,
            F_State:this.ruleForm.taskStateId,
            F_Remindertime:this.ruleForm.reminderTime,
            F_Parentid:this.parentId,
          }

          // 添加
          if (!this.rowid) {
            addTask(datas).then(response => {
              this.loading = false
              if (response.state.toLowerCase() === 'success') {
                this.$parent.$layer.close(this.layerid)
                this.$parent.getList() // 重新加载父级数据
                this.$message.success('恭喜你，任务信息添加成功!')
              }
            }).catch(() => {
              this.loading = false
            })
            return
          }
          // 编辑
          editTask(datas).then(response => {
            this.loading = false
            if (response.state.toLowerCase() === 'success') {
              this.$parent.$layer.close(this.layerid)
              this.$parent.getList() // 重新加载父级数据
              this.$message.success('恭喜你，任务信息编辑成功!')
            }
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.$message.error('请输入有效的必填项信息!')
          return false
        }
      })
    },
    resetForm() {
      this.ruleForm.currentAmount=''
      this.$refs.ruleForm.resetFields()
    },
    // 获取详情
    getDetail(rid) {
      getTask(rid).then(response => {
        if (response.state.toLowerCase() === 'success') {
          const res = response.data
          this.ruleForm.name = res.F_Name
          this.ruleForm.taskDate = [res.F_StartTime,res.F_EndTime]
          this.ruleForm.content = res.F_Content
          this.ruleForm.taskTypeId = res.F_Type
          this.ruleForm.taskStateId = res.F_State
          this.ruleForm.person = res.F_Tasker
          this.ruleForm.targetAmount = res.F_Money
          this.ruleForm.currentAmount = res.F_Currentamount
          this.ruleForm.reminderTime = res.F_Remindertime
          this.ruleForm.depid = res.F_Deptid&&res.F_Deptid.split(',').map(Number)
          if(res.F_Deptid){
            this.handleTaskMan()
          }
          this.ruleForm.person = res.F_Tasker==0?'':res.F_Tasker
        }
      })
    },
    handleChange(e){
      if(e){
        this.ruleForm.personId=e
      }
    },
    //获取任务部门
    getDepartment(){
       getDepartmentTreeList().then(response=>{
        if(response.state.toLowerCase()=='success'){
          this.depData=response.data
        }
      })
    },
    //获取任务人数据
    handleTaskMan(){
      this.ruleForm.person=''
      return new Promise(resolve=>{
        const params={
          deptid:this.ruleForm.depid&&this.ruleForm.depid[this.ruleForm.depid.length-1]
        }
        getTaskmanData(params).then(response=>{
          if(response.state.toLowerCase()=='success'){
            this.taskMan=response.data
          }
        }).catch(result=>{
          console.log(result)
        })
      })
    },
    //限制输入小数
    handleInput(e) {
        e.target.value = (e.target.value.match(/^\d*(\.?\d{0,2})/g)[0]) || null
    },

  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
	.date_picker{
		width: 100%;
	}
	div.date_picker input.el-range-input{
		width: 46%;
	}
</style>
