<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="120px">
        <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="expectedCompleteTime" >
          <el-date-picker
            v-model="formData.expectedCompleteTime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="请选择"
            :style="{width: '100%'}"
            >
          </el-date-picker>
        </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-item label="图片" v-if="mode !== 'add' && formData.images && formData.images.length>0">
          <img v-for="item in formData.images" :key="item+'imgs'" :src="item" alt="" srcset="" class="ticket-imgs">
        </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: '',//提交时间
        expectedCompleteTime:'',//预计完成时间
        images:[],//图片列表
      },
      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'] }
        ],
        expectedCompleteTime:[
          { 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 || {}));
            const {images=''} = this.formData
            this.formData.images = JSON.parse(images)
          }).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='',expectedCompleteTime=''} = this.formData;
        if(this.mode === 'add'){
          addTicket({title,content,status,userId,workUserId,expectedCompleteTime}).then(response => {
            if(response.code === 200){
              //新增成功
              // 关闭弹窗 更新表格
              this.$emit('update')
              this.closeDialog()
            }
          }).finally(() => {
            this.loading-=1
          })
        }else{
          updateTicket({title,content,status,userId,workUserId,id,expectedCompleteTime}).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:'',//工单号
        expectedCompleteTime:'',
        images: []
      }
      this.dialogTableVisible=false
    }
  }
}

</script>
<style scoped>
.ticket-imgs{
  width:150px;
  height: 100px;
}
</style>
