<template>
  <div class="container">
    <el-form :model="form" label-position="top" :rules="rules" ref="form" label-width="80px">
      <el-form-item label="出差人" prop="employeeName">
        <el-input v-model="form.employeeName" placeholder='点击选择' readonly @click.native="openSingle"></el-input>
      </el-form-item>
      <el-form-item label="Id" style="display: none;">
        <el-input v-model="form.employeeId" placeholder='Id' disabled></el-input>
      </el-form-item>
      <el-form-item label="部门">
        <el-input v-model="form.deptName" placeholder='部门' disabled></el-input>
      </el-form-item>
      <el-form-item label="职位">
        <el-input v-model="form.position" placeholder='职位' disabled></el-input>
      </el-form-item>
       <el-form-item label="手机号">
        <el-input v-model="form.employeePhone" placeholder='手机号' disabled></el-input>
      </el-form-item>
      <el-form-item label="出差地点" prop="destination">
        <el-input maxlength="20" v-model="form.destination" placeholder='出差地点'></el-input>
      </el-form-item>
      <el-form-item label="出差开始日期" prop="startData">
        <el-date-picker value-format="yyyy-MM-dd" v-model="form.startData" type="date" placeholder="请选择日期"
          style="width: 100%;" @change="upDay">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="出差结束日期" prop="endData">
        <el-date-picker value-format="yyyy-MM-dd" v-model="form.endData" type="date" placeholder="请选择日期"
          style="width: 100%;" @change="upDay">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="出差天数">
        <el-input v-model="form.day" placeholder='出差天数' @input="changeDay()"></el-input>
      </el-form-item>
      <el-form-item label="预估费用(元)" prop="purchaseMoney">
        <el-input v-model="form.purchaseMoney" placeholder='预估费用' @input="changeMoney()"></el-input>
      </el-form-item>
      <el-form-item label="出差事由" prop="purpose">
        <el-input maxlength="200" rows="4" show-word-limit type="textarea" v-model="form.purpose"
          placeholder='出差的主要目的或需要完成的任务'></el-input>
      </el-form-item>
      <el-form-item label="附件">
        <el-upload :action="fileUrl" :headers="headers" :file-list="files" :on-success="handleFileSuccessCite"
          :before-upload="beforeUploadFile" :on-remove="handleRemove">
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="备注">
        <el-input maxlength="200" rows="4" show-word-limit type="textarea" v-model="form.remarks" placeholder="请填写备注" />
      </el-form-item>
      <el-form-item label="审批人" prop="peopleList">
        <el-input type="textarea" v-model="form.peopleList" style="display: none;" />
        <el-button class="button-new-tag" @click="openMultiple">+ 添加</el-button>
        <span :key="tag" v-for="tag in nikeNamelist">
          <i class="el-icon-arrow-right"></i>
          <el-tag type="info" closable :disable-transitions="false" @close="handleClose(tag)">
            <span class="user-avatar">{{ tag.substring(0, 1) || 'U' }}</span>
            {{ tag }}
          </el-tag>
        </span>

      </el-form-item>
      <el-form-item label="流程动态" v-if="tasks.length > 0">
        <el-timeline>
          <el-timeline-item v-for="(item, index) in tasks" :key="index" :icon="getTimelineItemIcon(item)"
            :type="getTimelineItemType(item)">
            <p style="font-weight: 700">任务：{{ item.name }}</p>
            <el-card :body-style="{ padding: '10px' }">
              <label v-if="item.assigneeUser" style="font-weight: normal; margin-right: 30px;">
                审批人：{{ item.assigneeUser.nickname }}
                <el-tag type="info" size="mini">{{ item.assigneeUser.deptName }}</el-tag>
              </label>
              <label style="font-weight: normal" v-if="item.createTime">创建时间：</label>
              <label style="color:#8a909c; font-weight: normal">{{ parseTime(item.createTime) }}</label>
              <label v-if="item.endTime" style="margin-left: 30px;font-weight: normal">审批时间：</label>
              <label v-if="item.endTime" style="color:#8a909c;font-weight: normal"> {{
                parseTime(item.endTime)
                }}</label>
              <!-- <label v-if="item.durationInMillis" style="margin-left: 30px;font-weight: normal">耗时：</label>
              <label v-if="item.durationInMillis" style="color:#8a909c;font-weight: normal">
                {{ getDateStar(item.durationInMillis) }} </label> -->
              <p v-if="item.reason">
                <el-tag :type="getTimelineItemType(item)">{{ item.reason }}</el-tag>
              </p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </el-form-item>
      <el-form-item>
        <div v-if="name=='todo'">
          <el-button type="primary" @click="onReCommit()" v-loading.fullscreen.lock="fullscreenLoading">提交</el-button>
          <el-button type="warning" @click="onClose()" v-loading.fullscreen.lock="fullscreenLoading">关闭</el-button>
        </div>
       <div v-else>
        <el-button type="primary" @click="onSubmit()" v-loading.fullscreen.lock="fullscreenLoading">提交</el-button>
        <el-button @click="onSave()" v-loading.fullscreen.lock="fullscreenLoading">暂存</el-button>
        <el-button v-if="form.auditStatus==0" type="danger" @click="onDelete()" v-loading.fullscreen.lock="fullscreenLoading">删除</el-button>
       </div>
      </el-form-item>
    </el-form>
    <PeopleSelect ref="peopleSelect" type="multiple" :isCheck="true" :open="multiplePeopleOpen"
      @cancel="multiplePeopleOpen = false" @submit="submitMultiple"></PeopleSelect>
    <PeopleSelect ref="peopleSelect" type="single" :isCheck="true" :open="singlePeopleOpen"
      @cancel="singlePeopleOpen = false" @submit="submitSingle"></PeopleSelect>

  </div>

</template>

<script>
import { getDetail, create,reCommit, save, deleteById,closeById } from "@/api/oa/business"
import {getDate} from "@/utils/dateUtils";
import { getUserProfile } from "@/api/system/user";
import { listDept } from "@/api/system/dept";
import PeopleSelect from "@/components/PeopleSelect/index.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getBaseHeader } from "@/utils/request";
export default {
  name: 'Index',
  components: {
    PeopleSelect,
    Treeselect,
  },
  props: {
    id: {
      type: [String, Number],
      default: undefined
    },
    name: {
      type: String,
      default: undefined
    },
  },
  data() {
    return {
      fullscreenLoading:false,
      tasks:[],
      loading:false,
      files: [],
      // 设置上传的请求头部
      headers: getBaseHeader(),
      // 上传的地址
      fileUrl: process.env.VUE_APP_BASE_API + '/admin-api/infra/file/uploaData',
      // fileUrl: 'http://192.168.100.249:48080/admin-api/infra/file/uploaData',
      // 部门树选项
      posOptions: [],
      deptOptions: [],
      nikeNamelist: [],
      form: {
        employeeName: undefined,
        employeeId: undefined,
        deptName: undefined,
        position: undefined,
        employeePhone:undefined,
        destination: undefined,

        startData: undefined,
        endData: undefined,
        day: undefined,
        purchaseMoney: undefined,
        purpose: undefined,

        fileIdList: undefined,
        remarks: undefined,
        peopleList: '',
      },


      rules: {
        employeeName: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
        destination: [
          { required: true, message: '请填写出差地点', trigger: 'blur' },
        ],
        startData: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
        endData: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
        purchaseMoney: [
          { required: true, message: "请填写预估费用", trigger: "blur" }
        ],
        purpose: [
          { required: true, message: "请填写出差事由", trigger: "blur" }
        ],
        peopleList: [
          { required: true, message: '请选择审批人', }
        ]
      },
      status: true,
      //是否打开选人组件，默认不打开
      multiplePeopleOpen: false,
      singlePeopleOpen: false,
      queryParams: {
        name: undefined,
        status: undefined
      },
    }
  },

  created() {
    this.getDeptList();
  },
  watch: {
    id: {
      immediate: true,
      handler(val) {
        if(val){
          this.getDetail(val);
        }else{
          // this.getUser();
        }
      }
    }
  },
  methods: {
    changeMoney(){
      let purchaseMoney = this.form.purchaseMoney;
      this.form.purchaseMoney = this.NumberCheck(purchaseMoney,2);
    },
    changeDay(){
      let day = this.form.day;
      this.form.day = this.NumberCheck(day,1);
    },

    NumberCheck(num,type) {
      console.log(num);
      var str = num;
      var len1 = str.substr(0, 1);
      var len2 = str.substr(1, 1);
      //如果第一位是0，第二位不是点，就用数字把点替换掉
      if (str.length > 1 && len1 == 0 && len2 != ".") {
        str = str.substr(1, 1);
      }
      //第一位不能是.
      if (len1 == ".") {
        str = "";
      }
      //限制只能输入一个小数点
      if (str.indexOf(".") != -1) {
        var str_ = str.substr(str.indexOf(".") + 1);
        if (str_.indexOf(".") != -1) {
          str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
        }
      }
      //正则替换，保留数字和小数点
      if(type==0){
        str = str.replace(/[^\d^\.]+/g,'')
      }
       //如果需要保留小数点后一位，则用下面公式
      if(type==1){
        str = str.match(/^\d+(?:\.\d{0,1})?/)
      }
       //如果需要保留小数点后两位，则用下面公式
      if(type==2){
        str = str.match(/^\d+(?:\.\d{0,2})?/)
      }
      return str;
    },
    upDay() {
      if (this.form.startData && this.form.endData) {
        debugger
        let Days = this.calLeaveDays();
        this.form.day = Days;
        console.log(this.form.day);
        if (Days <= 0) {
          this.form.startData = "";
          this.form.endData = "";
          this.form.day = "";
          this.$message.warning("起始日期小于结束日期，请重新选择！");
          return;
        }
      }

    },
    calLeaveDays() {
      var start_date = new Date();
      var end_date = new Date();
      start_date = new Date(this.form.startData + " 00:00:00");
      end_date = new Date(this.form.endData + " 24:00:00");
      console.log(start_date);
      console.log(end_date);
      //转成毫秒数，两个日期相减
      var days = end_date.getTime() - start_date.getTime();
      //转换成天数
      var day = days / (1000 * 60 * 60 * 24);
      console.log("day = ", day);
      return day;
    },
    getDateStar(ms) {
      return getDate(ms);
    },
    getUser() {
      getUserProfile().then(response => {
        let userInfo = response.data;
        this.form.employeeName = userInfo.nickname;
        this.form.deptName = userInfo.dept.name;
        this.form.position = userInfo.posts[0].name;
        this.form.employeePhone = userInfo.mobile;
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      let fileIds = [];
      for (let i in fileList) {
        let id = fileList[i].response.data.id;
        fileIds.push(id);
      }
      this.form.fileIdList = fileIds;
    },
    beforeUploadFile(file) {
      console.log(file);
      const size = file.size / 1024 / 1024;
      console.log(size);
      if (size > 5) {
        this.$message.error("文件大小不能超过5MB！");
        return false;
      }
    },
    handleFileSuccessCite(res, file, fileList) {
      console.log(file, fileList);
      console.log("------", "==========");
      console.log("res = ", res);

      let fileIds = [];
      for (let i in fileList) {
        let response = fileList[i].response;
        if (response.errno && response.errno != "0") {
          this.$message.error("该文件上传失败,已被移除,请重新上传!");
          // 上传失败移除该 file 对象
          fileList.splice(i, 1);
        } else {
          let id = fileList[i].response.data.id;
          fileIds.push(id);
        }
      }
      this.form.fileIdList = fileIds;
    },
    /** 获得表单信息 */
    getDetail(val) {
      this.$parent.$parent.detailLoading = true;
      getDetail(val).then(response => {
        this.$parent.$parent.detailLoading = false;
        this.form = response.data;
        let files = response.data.fileList;
        if (files) {
          this.files = [];
          for (let i in files) {
            let url = files[i].url;
            let name = files[i].name;
            let id = files[i].id;

            this.files.push({
              name: name,
              url: url,
              response: { error: "0", data: { url: url, id: id } },
            });
          }
        }
       
        if(response.data.auditUserList){
          let auditUserList = response.data.auditUserList;
          let peopleList = [];
          let nikeNamelist = [];
          auditUserList.map(item => {
            peopleList.push(item.id);
            nikeNamelist.push(item.nickname)
          });
          this.$set(this.form, 'peopleList', peopleList.join(','));
          this.nikeNamelist = nikeNamelist;
        } else{
          this.$set(this.form, 'peopleList', '');
          this.nikeNamelist = [];
        }
        this.tasks = response.data.auditRecordList?response.data.auditRecordList:[];
        
      });
    },
    /** 查询部门列表 */
    getDeptList() {
      listDept(this.queryParams).then(response => {
        this.deptOptions = this.handleTree(response.data, "id");
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    //提交
    onSubmit() {
      console.log(this.form);
      this.$refs.form.validate(valid => {
        if (valid) {
          console.log(this.form);
          this.form.startUserSelectAssignees = this.form.peopleList.split(',');
          this.form.auditPass = true;
          this.fullscreenLoading = true;
          create(this.form).then(response => {
            this.fullscreenLoading = false;
            this.$modal.msgSuccess("提交成功");
            if(this.id){
              this.$parent.$parent.closeEdit();
            }else{
              this.$parent.$parent.setStatus(2);
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
     //驳回或撤回后再次提交通用用事项审批流程信息
     onReCommit() {
      console.log(this.form);
      this.$refs.form.validate(valid => {
        if (valid) {
          console.log(this.form);
          this.form.startUserSelectAssignees = this.form.peopleList.split(',');
          this.form.auditPass = true;
          this.fullscreenLoading = true;
          reCommit(this.form).then(response => {
            this.fullscreenLoading = false;
            this.$modal.msgSuccess("提交成功");
            if(this.id){
              this.$parent.$parent.closeEdit();
            }else{
              this.$parent.$parent.setStatus(2);
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //暂存
    onSave() {
          if(this.form.peopleList){
            this.form.startUserSelectAssignees = this.form.peopleList.split(',');
          }
          this.form.auditPass = false;
          this.fullscreenLoading = true;
          save(this.form).then(response => {
            this.fullscreenLoading = false;
            this.$modal.msgSuccess("暂存成功");
            if(this.id){
              this.$parent.$parent.closeEdit();
            }else{
              this.$parent.$parent.setStatus(2);
            }
          });
    },
    //暂存删除
    async onDelete() {
      this.$modal.confirm('是否确认删除?').then(() => {
        this.fullscreenLoading = true;
        deleteById(this.id).then(response => {
          this.fullscreenLoading = false;
          this.$modal.msgSuccess("删除成功");
          this.$parent.$parent.closeEdit();
        })
      }).catch(() => { });
    },
     //暂存删除
     async onClose() {
      this.$modal.confirm('是否确认关闭?').then(() => {
        this.fullscreenLoading = true;
        closeById(this.id).then(response => {
          this.fullscreenLoading = false;
          this.$modal.msgSuccess("流程已关闭");
          this.$parent.$parent.closeEdit();
        })
      }).catch(() => { });
    },

     // 关闭标签
     handleClose(index) {
      this.nikeNamelist.splice(index, 1);
      let peopleList = this.form.peopleList.split(',');
      peopleList.splice(index, 1);
      this.form.peopleList = peopleList.join(',');
    },
    //打开选人弹窗
    openSingle() {
      this.singlePeopleOpen = true;
    },
    openMultiple() {
      this.multiplePeopleOpen = true;
    },
    //选择人的确定按钮事件 submitPeople(nikeNamelist)方法传参一个默认接收用户昵称数组   submitPeople(peopleList,nikeNamelist)方法传参两个则是接收用户昵称数组和用户账号数组
    submitMultiple(userNamelist, nikeNamelist,userIdList) {
      console.log(userNamelist);
      this.nikeNamelist = nikeNamelist;
      this.form.peopleList = userIdList.join(',');
      this.multiplePeopleOpen = false;
    },
    submitSingle(userNamelist, nikeNamelist,userIdList) {
      console.log(userNamelist);
      this.form.employeeName = nikeNamelist.join();
      this.form.employeeId = userIdList.join();
      this.singlePeopleOpen = false;
    },
    getTimelineItemIcon(item) {
      if (item.result === 1) {
        return 'el-icon-time';
      }
      if (item.result === 2) {
        return 'el-icon-check';
      }
      if (item.result === 3) {
        return 'el-icon-close';
      }
      if (item.result === 4) {
        return 'el-icon-remove-outline';
      }
      if (item.result === 5) {
        return 'el-icon-back'
      }
      return '';
    },
    getTimelineItemType(item) {
      if (item.result === 1) {
        return 'primary';
      }
      if (item.result === 2) {
        return 'success';
      }
      if (item.result === 3) {
        return 'danger';
      }
      if (item.result === 4) {
        return 'info';
      }
      if (item.result === 5) {
        return 'warning';
      }
      if (item.result === 6) {
        return 'default'
      }
      return '';
    },
  }
}
</script>
<style lang="scss" scoped>
.user-avatar {
  width: 22px;
  height: 22px;
  line-height: 19px;
  font-size: 12px;
  background: #46c26f;
  border: 1px solid transparent;
  border-radius: 50%;
  color: #fff;
  display: inline-block;
  overflow: hidden;
  text-align: center;
  vertical-align: middle;
  margin-bottom: 2px;
}

.el-tag+.el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-right: 10px;
  height: 30px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

ul {
  padding-left: 0px !important;
}

.el-tag+.el-tag {
  margin-left: 10px;
}
</style>