<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="申请时间" prop="leaveDate">
          <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleDateChange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="审批状态" prop="isCheck">
          <el-select
              v-model="queryParams.isCheck"
              placeholder="审批状态" style="width: 95%">
              <el-option
                v-for="dict in isCheckList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['att:org:change:add']"
          >新增</el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
          >导出</el-button>
        </el-col>

        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="tableList">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="序号" align="center" width="80" type="index">
          <template slot-scope="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="center" prop="userName" width="100"/>
        <el-table-column label="申请时间" align="center" prop="createTime" :show-overflow-tooltip="true" width="180"/>
        <el-table-column label="变更前部门" align="center" prop="oldOrgName" :show-overflow-tooltip="true" width="240">
        </el-table-column>
        <el-table-column label="变更后部门" align="center" prop="newOrgName" :show-overflow-tooltip="true" width="240">
        </el-table-column>
        <el-table-column label="考勤规则组变更" align="center" prop="isChangeAttGroup" :show-overflow-tooltip="true" width="180">
          <template slot-scope="scope">
              <div>
                <span v-show="scope.row.isChangeAttGroup=='1'">是</span>
                <span v-show="scope.row.isChangeAttGroup=='0'">否</span>
              </div>
          </template>
        </el-table-column>
        <el-table-column label="审批状态" align="center" prop="isCheck" :show-overflow-tooltip="true" width="100">
          <template slot-scope="scope">
            <span v-show="scope.row.isCheck=='0'">待审批</span>
            <span v-show="scope.row.isCheck=='1'">已通过</span>
            <span v-show="scope.row.isCheck=='2'">未通过</span>
            <span v-show="scope.row.isCheck=='3'">撤回</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              v-if="scope.row.isCheck==0||scope.row.isCheck==2||scope.row.isCheck==3"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['att:org:change:edit']"
            >编辑</el-button>
            <el-button
              size="mini"
              v-hasPermi="['att:org:change:query']"
              @click="handleView(scope.row)"
            >详情</el-button>
            <el-button
              size="mini"
              type="primary"
              v-hasPermi="['att:org:change:edit']"
              v-if="scope.row.isCheck==0"
              @click="handleBack(scope.row)"
            >撤回</el-button>
            <el-button
              size="mini"
              type="danger"
              v-hasPermi="['att:org:change:remove']"
              v-if="scope.row.isCheck==0||scope.row.isCheck==2||scope.row.isCheck==3"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改参数配置对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="170px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="申请人：" prop="userName">
                <el-input v-model="form.userName" :readonly="true" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="变更前部门:" prop="oldOrgId" >
                <el-select v-model="form.oldOrgId" @change="changDept" :disabled="isView" style="width: 100%">
                  <el-option
                    v-for="item in orgList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="变更后部门:" prop="newOrgId" >
                <el-select v-model="form.newOrgId" @change="changDept" :disabled="isView" style="width: 100%">
                  <el-option
                    v-for="item in orgList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="考勤规则组变更："  prop="isChangeAttGroup">
                <el-radio-group v-model="form.isChangeAttGroup">
                  <el-radio
                    v-for="item in isAgreeList"
                    :key="item.id"
                    :label="item.id"
                  >{{item.name}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row  v-if="form.isChangeAttGroup == '1'">
            <el-col :span="12">
              <el-form-item label="变更前规则组：" prop="attGroupName">
                <el-input v-model="form.attGroupName" :readonly="true" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="变更后规则组：" prop="newAttGroup">
                <el-select v-model="form.newAttGroup"   placeholder="请选择" filterable  style="width: 100%;" :disabled="isView">
                  <el-option
                    v-for="item in userList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="变更生效日期：" prop="changeEffectiveDate">
                <el-date-picker
                  v-model="form.changeEffectiveDate" :clearable="false" :disabled="isView"
                  type="date" value-format="yyyy-MM-dd" style="width: 100%;"
                  placeholder="变更生效日期" >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注：">
                <el-input type="textarea" placeholder="输入内容" v-model="form.remark" maxlength="100" :readonly="isView"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm" v-if="!isView">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>

  <script>
  import {
    listOrg, getOrg, delOrg, addOrg, updateOrg, changeOrgStatus, exportOrg, getPostName,
    getAttGroupList,
  } from "@/api/process/orgApply";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  export default {
    name: "OrgApply",
    data() {
      return {
        //申请人
        userInfo:this.$store.state.user,
        //组织机构
        orgList:this.$store.state.user.orgList,
        //审核状态
        isCheckList:[{id:'0',name:"待审批"},{id:'1',name:"已通过"},{id:'2',name:"未通过"},{id:'3',name:"撤回"}],
        // 遮罩层
        loading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 表格数据
        tableList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        isEdit: false,
        isView: false,
        userList:[],
        isAgreeList:[{id:'0',name:'否'},{id:'1',name:'是'}],
        // 日期范围
        dateRange: [],
        startTime: '', // 存储开始时间
        endTime: '',   // 存储结束时间
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          isCheck: undefined
        },
        personOptions:[],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          userName:[
            {required: true, message: "申请人不能为空", trigger: "blur" }
          ],
          postName:[
            {required: true, message: "职务不能为空", trigger: "blur" }
          ],
          oldOrgId: [
            { required: true, message: "变更前部门不能为空", trigger: "blur" }
          ],
          newOrgId: [
            { required: true, message: "变更后部门不能为空", trigger: "blur" }
          ],
          changeEffectiveDate: [
            { required: true, message: "变更生效日期不能为空", trigger: "blur" }
          ],
          leaveStartInterval: [
            { required: true, message: "不能为空", trigger: "change" }
          ],
          isChangeAttGroup:[
            { required: true, message: "是否考勤规则组变更不能为空", trigger: "blur" }
          ],
          newAttGroup:[
            { required: true, message: "变更后规则组不能为空", trigger: "blur" }
          ]
        },

        // 结束日期选择限制
        endPickerOptions: {
            disabledDate: (v) => {
                if(this.form.changeEffectiveDate) {
                    return v.getTime() < new Date(this.form.changeEffectiveDate).getTime() - 86400000; //  - 86400000是否包括当天
                }
            },
        },
      };
    },
    created() {
      this.getList();

      this.getUserLists();
    },
    methods: {
      handleDateChange(value) {
        if (value && value.length === 2) {
          this.startTime = value[0];
          this.endTime = value[1];
        } else {
          // 如果没有选择完整日期范围，可以清空 startTime 和 endTime
          this.startTime = '';
          this.endTime = '';
        }
      },
      daysBetween(date1, date2){
        const oneDay = 24 * 60 * 60 * 1000;
        const date1Ms = new Date(date1).getTime()
        const date2Ms = new Date(date2).getTime()
        const diff = Math.abs(date1Ms - date2Ms); // 计算两日期的差值
        return diff / oneDay; // 返回天数
      },
      /** 查询列表 */
      getList() {
        this.loading = true;
        this.queryParams.startTime= this.startTime;
        this.queryParams.endTime= this.endTime;
        listOrg(this.queryParams).then(response => {
            this.tableList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      getUserLists(){
        getAttGroupList().then(response => {
          this.userList = response.data;
          console.log("userList",this.userList)
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          userId:this.userInfo.id,
          userName:this.userInfo.name,
          newOrgId: undefined,
          changeEffectiveDate: undefined,
          leaveStartInterval:undefined,
          isCheck:"0",
          isChangeAttGroup: "0",
          leaveReason:undefined,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.startTime="";
        this.endTime = "";
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        const Id = this.$store.state.user.id;
        getPostName(Id).then(response => {
          this.form.postName = response.data.postName;
          //变更前部门
          this.form.attGroupId = this.$store.state.user.attGroupId;
          this.form.attGroupName = this.$store.state.user.attGroupName;
          this.open = true;
          this.isView = false;
          this.title = "新增";
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const Id = row.id
        getOrg(Id).then(orgResponse => {
          // 更新表单的 org 信息
          this.form = orgResponse.data;
          this.form.attGroupName = orgResponse.data.oldOrgName;
          // 更新视图状态
          this.open = true;
          this.isView = false;
          this.title = "编辑";
        });
      },
      handleView(row) {
        this.reset();
        const Id = row.id
        getOrg(Id).then(orgResponse => {
          // 更新表单的 org 信息
          this.form = orgResponse.data;
          this.form.attGroupName = orgResponse.data.oldOrgName;
          // 更新视图状态
          this.open = true;
          this.isView = true;
          this.title = "查看";
        });
      },
      //选择部门
      changDept(e){
        console.log(e)
        this.orgList.forEach(item=>{
          if(item.id==e){
            this.form.orgName = item.name
          }
        })
      },
      /** 提交按钮 */
      submitForm: function() {
        console.log(this.form)
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.isCheck = '0';
            if (this.form.id != undefined) {
              updateOrg(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              this.form.oldAttGroup = this.$store.state.user.attGroupId;
              addOrg(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      handleBack(row) {
        var that = this;
        this.$modal.confirm('是否确认撤回该申请？').then(function() {
          let param = {
            id:row.id,
            isCheck:'3',
          }
          changeOrgStatus(param).then(response => {
            that.getList();
            this.$modal.msgSuccess("撤回成功");
          });
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const Ids = row.id;
        this.$modal.confirm('是否确认删除该申请？').then(function() {
          return delOrg(Ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.queryParams.startTime= this.startTime;
        this.queryParams.endTime= this.endTime;
        // this.queryParams.exportType="查询";
        exportOrg(this.queryParams).then(res => {
          this.downloadFile({ fileName: `组织架构变更申请_${new Date().getTime()}.xlsx`, fileData: res, fileType: 'application/vnd.ms-excel;charset=utf-8' })
        })
      },

    }
  };
  </script>
