<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="expenseTypeId">
        <el-select v-model="form.expenseTypeId" placeholder="请选择" style="width: 100%;" @change="getListByExpenseTypeId()">
          <el-option v-for="item in typeList" :key="item.id" :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="费用所属期间" prop="expenseMonth">
        <el-date-picker value-format="yyyy-MM" v-model="form.expenseMonth" type="month" placeholder="选择日期"
          style="width: 100%;">
        </el-date-picker>
      </el-form-item>
      <el-button style="margin-bottom: 10px;" type="success" size="small" @click="addRow">新增</el-button>
      <!--表格里面嵌套表单-->
      <el-table border :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
        :data="form.oaExpenseObjs" ref="table" style="width: 100%">

       

        <el-table-column label="费用项目" width="300">
          <template slot-scope="scope">
            <el-form-item  :prop="'oaExpenseObjs.' + scope.$index + '.expenseItemId'"
              :rules="{ required: true, message: '费用项目不能为空', trigger: 'blur' }">
              <el-select v-model="form.oaExpenseObjs[scope.$index].expenseItemId" placeholder="请选择费用项目" style="width: 100%;" size="small">
                <el-option v-for="item in listByExpenseType" :key="item.id" :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="金额(元)" width="200">
          <template slot-scope="scope">
            <el-form-item  :prop="'oaExpenseObjs.' + scope.$index + '.money'"
              :rules="{ required: true, message: '金额不能为空', trigger: 'blur' }">
              <el-input v-model="form.oaExpenseObjs[scope.$index].money" autocomplete="off" size="small"
                placeholder="金额" oninput="value=value.match(/\d+\.?\d{0,2}/,'')"  @input="changeMoney(scope.$index)"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="开始日期" width="200">
          <template slot-scope="scope">
            <el-form-item  :prop="'oaExpenseObjs.' + scope.$index + '.startDate'"
              :rules="{ required: true, message: '开始日期不能为空', trigger: 'blur' }">
              <el-date-picker value-format="yyyy-MM-dd" v-model="form.oaExpenseObjs[scope.$index].startDate" type="date" placeholder="选择日期"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="结束日期" width="200">
          <template slot-scope="scope">
            <el-form-item  :prop="'oaExpenseObjs.' + scope.$index + '.endDate'"
              :rules="{ required: true, message: '结束日期不能为空', trigger: 'blur' }">
              <el-date-picker value-format="yyyy-MM-dd" v-model="form.oaExpenseObjs[scope.$index].endDate" type="date" placeholder="选择日期"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="说明" width="500">
          <template slot-scope="scope">
            <el-form-item  :prop="'oaExpenseObjs.' + scope.$index + '.remarks'"
              :rules="{ required: true, message: '说明不能为空', trigger: 'blur' }">
              <el-input maxlength="20" v-model="form.oaExpenseObjs[scope.$index].remarks" autocomplete="off" size="small"
                placeholder="说明名称"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="80">
          <template slot-scope="scope">
            <el-button :disabled="form.oaExpenseObjs.length > 1 ? false : true" style="margin-bottom: 22px;" @click="handleDeleteRow(scope.$index)"
              type="text" size="small">删除</el-button>
          </template>
        </el-table-column>

      </el-table>
      <el-form-item label="报销总金额(元)" prop="totalMoney">
        <el-input type="number" v-model="form.totalMoney" placeholder='报销总金额' disabled></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,listByExpenseTypeId, getDetail, create, reCommit, save, deleteById, closeById } from "@/api/oa/expense"
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',
      // 部门树选项
      typeList: [],
      listByExpenseType: [],
      deptOptions: [],
      nikeNamelist: [],
      form: {
        employeeName: undefined,
        deptName: undefined,
        position: undefined,
        employeePhone: undefined,
        expenseTypeId: undefined,
        expenseMonth: undefined,
        oaExpenseObjs: [],
        totalMoney: undefined,
        fileIdList: undefined,
        remarks: undefined,
        peopleList: '',
      },
      rules: {
        expenseTypeId: [
          { required: true, message: '请选择报销类型', trigger: 'change' }
        ],
        expenseMonth: [
          { required: true, message: '请选择费用所属期间', trigger: 'change' }
        ],
        totalMoney: [
          { required: true, message: '请输入报销总金额', trigger: 'blur' }
        ],
        peopleList: [
          { required: true, message: '请选择审批人', }
        ]
      },
      status: true,

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

  created() {
    this.getTypeList();
    // this.getDeptList();
  },
  watch: {
    id: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getDetail(val);
        } else {
          this.getUser();
          this.addRow();
        }
      }
    }
  },
  methods: {
    // 报销类型信息列表
    getTypeList(){
      typeList().then(
        response => {
          this.typeList = response.data;
        }
      );
    },
    //获得报销费用项目信息列表

    getListByExpenseTypeId(){
      listByExpenseTypeId({expenseTypeId:this.form.expenseTypeId}).then(
        response => {
          this.listByExpenseType = response.data;
        }
      );
    },
    changeMoney(index){
      if(this.form.oaExpenseObjs[index].money){
        let money = this.form.oaExpenseObjs[index].money;
        this.form.oaExpenseObjs[index].money = money;
        let arr = this.form.oaExpenseObjs;
        this.form.totalMoney = this.sum(arr);
      }
    },
    //求和
    sum(arr){
      return arr.reduce((prev,cur)=>{
        return ((prev* 100) + (cur.money * 100))/100
      },0)
    },
    /**
  * 新增行
  */
    addRow() {
      this.form.oaExpenseObjs.push({
        expenseItemId: '',
        money: '',
        startDate: '',
        endDate: '',
        remarks: '',
      });
    },

    /**
     * 删除行
     * @param row
     */
    handleDeleteRow(index) {
      this.form.oaExpenseObjs.splice(index, 1);
      let arr = this.form.oaExpenseObjs;
      this.form.totalMoney = this.sum(arr);
    },
    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;
        if(response.data.expenseTypeId){
          this.getListByExpenseTypeId();
        }
        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>