<template>
  <div class="contents">
    <el-form :model="form" label-position="top" :rules="rules" ref="form" label-width="80px">
      <el-form-item label="用印人">
        <el-input v-model="form.employeeName" disabled></el-input>
      </el-form-item>
      <el-form-item label="部门">
        <el-input v-model="form.deptName" disabled></el-input>
      </el-form-item>
      <el-form-item label="职位">
        <el-input v-model="form.position" disabled></el-input>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="form.employeePhone" disabled></el-input>
      </el-form-item>
      <el-form-item label="用印标题" prop="stampTitle">
        <el-input maxlength="20" v-model="form.stampTitle" placeholder='请输入申请的简要标题'></el-input>
      </el-form-item>
      <el-form-item label="用章类型" prop="stampSealId">
        <el-checkbox-group v-model="form.stampSealId">
          <el-checkbox v-for="item in oaStampSeal" :label="item.id" :key="item.id">{{item.sealName}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="用印事由" prop="reason">
        <el-input maxlength="50" show-word-limit type="textarea" v-model="form.reason"
          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 v-model="form.peopleList" style="display: none;" />
        <el-button class="button-new-tag" @click="openPS">+ 添加</el-button>
        <span v-for="(tag,index) in nikeNamelist" :key="index" >
          <i class="el-icon-arrow-right"></i>
          <el-tag type="info" closable :disable-transitions="false" @close="handleClose(index)">
            <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="type" :isCheck="true" :open="peopleOpen" @cancel="peopleOpen = false"
      @submit="submitPeople"></PeopleSelect>

  </div>

</template>

<script>
import { typeList,getDetail, create,reCommit, save, deleteById,closeById } from "@/api/oa/stamp"
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 {
      oaStampSeal:[],
      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,
        deptName: undefined,
        position: undefined,
        employeePhone: undefined,
        stampTitle: undefined,
        stampSealId: [],
        reason: undefined,
        fileIdList: undefined,
        remarks: undefined,
        peopleList: '',
      },
      rules: {
        stampTitle: [
          { required: true, message: '请输入申请的简要标题', trigger: 'blur' },
        ],
        stampSealId: [
          { required: true, message: '请选择印章类型', trigger: 'blur' },
        ],
        reason: [
          { required: true, message: '请输入详细描述', trigger: 'blur' }
        ],
        peopleList: [
          { required: true, message: '请选择审批人', }
        ]
      },
      status: true,

      type: 'multiple',
      //是否打开选人组件，默认不打开
      peopleOpen: false,
      queryParams: {
        name: undefined,
        status: undefined
      },
    }
  },

  created() {
    this.getDeptList();
    this.getTypeList();
  },
  watch: {
    id: {
      immediate: true,
      handler(val) {
        if(val){
          this.getDetail(val);
        }else{
          this.getUser();
        }
      }
    }
  },
  methods: {
    // 类型信息列表
    getTypeList(){
      typeList().then(
        response => {
          this.oaStampSeal = response.data;
        }
      );
    },
    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(',');
    },
    //打开选人弹窗
    openPS() {
      this.peopleOpen = true;
    },
    //选择人的确定按钮事件 submitPeople(nikeNamelist)方法传参一个默认接收用户昵称数组   submitPeople(peopleList,nikeNamelist)方法传参两个则是接收用户昵称数组和用户账号数组
    submitPeople(userNamelist, nikeNamelist,userIdList) {
      console.log(userNamelist);
      this.nikeNamelist = nikeNamelist;
      this.form.peopleList = userIdList.join(',');
      this.peopleOpen = 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>