<template>
  <div class="container">
    <el-row :gutter="20">
      <el-col :xl="12" :lg="12" :md="12" :sm="12" :xs="24">
        <el-form ref="form" :model="projectFrom" label-width="120px" :rules="rules">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="projectFrom.projectName"></el-input>
          </el-form-item>
          <el-form-item label="项目编号" prop="projectNumber">
            <el-input v-model="projectFrom.projectNumber"></el-input>
          </el-form-item>
          <el-form-item label="项目合同金额" prop="projectAmount">
            <el-input v-model="projectFrom.projectAmount"></el-input>
          </el-form-item>
          <el-form-item label="项目总收入" prop="projectIncome">
            <el-input v-model="projectFrom.projectIncome" disabled></el-input>
          </el-form-item>
          <el-form-item label="项目总支出" prop="projectExpend">
            <el-input v-model="projectFrom.projectExpend" disabled></el-input>
          </el-form-item>
          <el-form-item label="项目总报销" prop="projectExpense">
            <el-input v-model="projectFrom.projectExpense" disabled></el-input>
          </el-form-item>
          <el-form-item label="项目合作方" prop="projectPartyb">
            <el-input v-model="projectFrom.projectPartyb"></el-input>
          </el-form-item>
          <el-form-item label="项目时间" prop="timeSlot">
            <el-date-picker
              v-model="projectFrom.timeSlot"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="time"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="项目详情" prop="projectInformation">
            <el-input
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 6}"
              placeholder="请输入内容"
              v-model="projectFrom.projectInformation"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="success" icon="el-icon-upload2" @click="submitForm()">提交</el-button>
            <el-button type="info" icon="el-icon-refresh-left" @click="resetForm()">重置信息</el-button>
            <el-button @click="back()">返回</el-button>
          </el-form-item>
        </el-form>
      </el-col>

      <el-col :xl="12" :lg="12" :md="12" :sm="12" :xs="24">
        <div>
          负责人：
          <el-tag
            :key="projectLeader"
            v-for="(projectLeader,index) in projectLeaderList"
            closable
            :disable-transitions="false"
            @close="delectTag(index)"
            style="margin:0px 10px"
          >{{projectLeader}}</el-tag>
        </div>
        <div class="projectLeader">
          <div style="marrgin">选择区：</div>
          <div style="padding:20px">
            角色：
            <el-select v-model="personListForm.rlId" placeholder="请选择" @change="selsetperson()">
              <el-option
                v-for="item in rolesList"
                :key="item.rlId"
                :label="item.rlName"
                :value="item.rlId"
              ></el-option>
            </el-select>
            <!--<el-button type="primary" @click="selsetperson()" :disabled="isgetrules">搜索</el-button>-->
            <div class="personList">
              <el-checkbox-group v-model="projectLeaderList">
                <el-checkbox
                  :label="ch.userName"
                  v-for="ch in checkList"
                  :key="ch.userId"
                  :value="ch.userId"
                  @change="AddSelect(ch.userId)"
                ></el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { insert } from "@/api/project";
import { selectAllByCompanyId, insertBatch, secletAllByRlid } from "@/api/role";
export default {
  data() {
    return {
      //查询员工的数组
      checkList: [],
      //收集查询员工数据
      list: {
        rlId: 0,
        companyId: 0
      },
      //添加负责人数组
      insertBatch: [],
      projectFrom: {
        projectName: null,
        projectNumber: null,
        projectAmount: null,
        projectIncome: 0,
        projectExpend: 0,
        projectExpense: 0,
        projectStartTime: null,
        projectEndTime: null,
        projectFile: null,
        userId: null,
        companyId: null,

        projectPartyb: null,
        projectInformation: null,

        timeSlot: null
      },
      rules: {
        projectName: [
          { required: true, message: "请输入项目名称", trigger: "blur" }
        ],
        projectNumber: [
          { required: true, message: "请输入项目编号", trigger: "blur" }
        ],
        projectAmount: [
          {
            required: true,
            message: "请输入项目合同金额（起始金额）",
            trigger: "blur"
          }
        ],
        timeSlot: [
          { required: true, message: "请选择日期", trigger: "change" }
        ],

        projectPartyb: [
          {
            required: true,
            message: "请输入项目合作方",
            trigger: "blur"
          }
        ]
      },
      isgetrules: false,
      //显示tag
      projectLeaderList: [],
      rolesList: [], //角色列表
      personList: [], //员工列表
      //收集userId
      userIdAdd: [],
      personListForm: {
        rlId: null
      }
    };
  },
  created() {
    this.projectFrom.userId = this.$store.getters.urId;
    this.projectFrom.companyId = this.$store.getters.companyId;
    this.getRoleList();
  },
  methods: {
    //获取公司全部角色
    getRoleList() {
      selectAllByCompanyId({ companyId: this.$store.getters.companyId })
        .then(res => {
          if (res.status == "success") {
            this.rolesList = res.data;
          } else {
            this.$message.error(res.data);
          }
        })
        .catch(error => {
          this.$message.error("查询数据失败");
        });
      //添加负责人
    },
    //查询员工
    async selsetperson() {
      this.list.rlId = this.personListForm.rlId;
      this.list.companyId = this.$store.getters.companyId;
      let result = await secletAllByRlid(this.list);
      if (result.code == 20000) {
        this.checkList = result.data;
      }
    },
    //删除
    delectTag(index) {
      this.projectLeaderList.splice(index, 1);
      this.userIdAdd.splice(index, 1);
    },
    //projectId:0,
    //userId:this.checkList.userId,
    //memberId: 0
    AddSelect(row) {
      //定义一个对象
      let attr = {};
      this.projectLeaderList.forEach((item, index) => {
        attr.userId = row;
        attr.projectId = 0;
        attr.memberPression = 0;
      });
      this.userIdAdd.push(attr);
    },
  
    //时间处理
    time(val) {
      if (val == null) {
        this.projectFrom.projectStartTime = null;
        this.projectFrom.projectEndTime = null;
      } else {
        this.projectFrom.projectStartTime = this.timestampToTime(val[0]);
        this.projectFrom.projectEndTime = this.timestampToTime(val[1]);
      }
    },
    //重置数据
    resetForm() {
      this.$refs.form.resetFields();
    },
    //提交数据
    submitForm() {
      //第一步校验数据完整性
      this.$refs.form.validate(valid => {
        if (this.projectLeaderList.length < 1) {
          this.$message.warning("请选择项目负责人");
        } else if (valid) {
          //第四步提交
          console.log(this.projectFrom);
          insert(this.projectFrom)
            .then(res => {
              if (res.success) {
                let dateadd = [];
                this.userIdAdd.forEach(item => {
                  dateadd.push({
                    userId: item.userId,
                    projectId:res.data,
                    memberPression: 0
                  });
                });
                console.log(dateadd);
                let restle = insertBatch(dateadd);
                if (restle.success = true) {
                  console.log("保存成功");
                  this.$message.success("新建成功");
                  this.back();
                } else {
                  this.$message.success("发生错误");
                }
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch(error => {
              this.$message.error("插入失败");
            });
        }
      });
    },
    //返回
    back() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push("/projectList");
    },
    //时间处理
    timestampToTime(date) {
      var Y = date.getFullYear() + "-";
      var M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      var h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var m =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    }
  }
};
</script>

<style scoped>
.container {
  padding: 10px;
}
.projectLeader {
  width: 100%;
  border: 1px solid black;
  margin: 20px 0px;
  padding: 20px;
  border-radius: 20px;
  box-shadow: 1px 1px 1px black;
}
.personList {
  margin-top: 20px;
}
</style>