<template>
    <el-dialog v-loading="loading>0" :visible.sync="dialogTableVisible" class="ems-dialog" :title="mode === 'add'?'新增工单':`编辑工单` " :close-on-click-modal="false" :show-close="false">
      <el-form ref="addTempForm" :model="formData" :rules="rules" size="medium" label-width="100px">
        <el-form-item label="工单号" prop="ticketNo" v-if="mode !== 'add'">
          <el-input disabled v-model="formData.ticketNo" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="工单标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="问题描述" prop="content">
          <el-input v-model="formData.content" type="textarea" placeholder="请输入" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择" :style="{width: '100%'}">
            <el-option :label="value" :value="parseInt(key)" v-for="(value,key) in ticketStatusOptions" :key="key+'ticketStatusOptions'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="提交人" prop="userId">
          <el-select v-model="formData.userId" placeholder="请选择" :style="{width: '100%'}">
            <el-option :label="item.userName" :value="item.userId" v-for="(item,index) in userList" :key="index+'createUserList'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理人" prop="workUserId">
          <el-select v-model="formData.workUserId" placeholder="请选择" :style="{width: '100%'}">
            <el-option :label="item.userName" :value="item.userId" v-for="(item,index) in userList" :key="index+'updateUserList'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="提交时间" prop="createTime" v-if="mode !== 'add'">
          <el-input v-model="formData.createTime"  disabled :style="{width: '100%'}">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveDialog">确定</el-button>
      </div>
    </el-dialog>
</template>
<script>
import {mapState} from "vuex";
import {getTicket,getAllUser,addTicket,updateTicket} from'@/api/ems/ticket'
import {validText} from '@/utils/validate'
export default {
  props:{
    mode:{
      type:String,
      default:"add"
    },
    id:{
      type:String,
      required:false
    }
  },
  data() {
    const validateContent=(rule, value, callback) =>{
      if (value === '') {
        callback(new Error(`请输入${rule.field === 'title' ?'工单标题' :'问题描述'}`));
      } else if (!validText(value)) {
        callback(new Error('只能输入中文、英文、数字和特殊字符!'));
      } else {
        callback();
      }
    }
    return {
      loading:0,
      dialogTableVisible:false,
      userList:[],
      formData: {
        id:'',
        ticketNo:'',//工单号
        title: '',//工单标题
        content: '',
        status:'',
        createBy:'',//提交人
        userId:'',//提交人id
        updateBy: '',//处理人
        workUserId:'',//处理人id
        createTime: '',//提交时间
      },
      rules: {
        title:[
          { validator: validateContent, trigger: 'blur' }
        ],
        content:[
          { validator: validateContent, trigger: 'blur' }
        ],
        status:[
          { required: true, message: '请选择工单状态', trigger: ['blur', 'change']}
        ],
        userId:[
          { required: true, message: '请选择提交人', trigger: ['blur', 'change'] }
        ],
        workUserId:[
          { required: true, message: '请选择处理人', trigger: ['blur', 'change'] }
        ]
      },
    }
  },
  computed: {
    ...mapState({
      ticketStatusOptions: state => state?.ems?.ticketStatusOptions || {},
    })
  },
  watch:{
    dialogTableVisible:{
      handler(newVal){
        newVal && this.getUserList()
      },
      immediate: true,
    },
    id:{
      handler(newVal){
        if(newVal && this.mode !== 'add'){
          //获取详情
          this.loading+=1
          getTicket(newVal).then(response => {
            this.formData = JSON.parse(JSON.stringify(response?.data || {}));
          }).finally(() => {this.loading-=1})
        }
      },
      immediate: true,
    }
  },
  methods: {
    getUserList(){
      this.loading= this.loading+1
      getAllUser().then(response => {
        this.userList = JSON.parse(JSON.stringify(response?.data || []));
      }).finally(() => {
        this.loading=this.loading -1
      })
    },
    saveDialog() {
      this.$refs.addTempForm.validate(valid => {
        if (!valid) return
        this.loading+=1
        const {title='',content='',status='',userId='',workUserId='',id=''} = this.formData;
        if(this.mode === 'add'){
          addTicket({title,content,status,userId,workUserId}).then(response => {
            if(response.code === 200){
              //新增成功
              // 关闭弹窗 更新表格
              this.$emit('update')
              this.closeDialog()
            }
          }).finally(() => {
            this.loading-=1
          })
        }else{
          updateTicket({title,content,status,userId,workUserId,id}).then(response => {
            if(response.code === 200){
              //新增成功
              // 关闭弹窗 更新表格
              this.$emit('update')
              this.closeDialog()
            }
          }).finally(() => {
            this.loading-=1
          })
        }

      })
    },
    closeDialog(){
      // 清空所有数据
      this.$emit('clear')
      this.$refs.addTempForm.resetFields()
      this.formData={
        title: '',//工单标题
        content: '',
        status:'',
        createBy:'',//提交人
        userId:'',//提交人id
        updateBy: '',//处理人
        workUserId:'',//处理人id
        completeTime: '',//提交时间
        ticketNo:'',//工单号
      }
      this.dialogTableVisible=false
    }
  }
}

</script>
<style scoped>
.ems-dialog{
  .el-dialog{
    max-width: 700px;
  }
}
</style>
