<template>
  <div class="bigBox" :style="{ height: bigHeight }">
    <MOSTY.FromPage :title="props.title" @closeDialog="black">
      <template #content>
        <MOSTY.Assort :title="'值班信息'" />
        <div class='fromBox'>
          <el-form class="mosty-from-wrap" ref="ruleFormRef" label-width="130px" :model="data.fromObj" :inline="true"
            :rules="rules" :disabled="!props.saveBtnShow" style='margin-top:10px;'>
            <el-form-item label="值班名称:" prop="ondutyname">
              <el-input v-model="data.fromObj.ondutyname" clearable style="width: 715px" />
            </el-form-item>
            <el-form-item label="值班地点:" prop="ondutysite">
              <el-input v-model="data.fromObj.ondutysite" clearable style="width: 715px" />
            </el-form-item>
            <el-form-item label="开始时间:" prop="begintime">
              <el-date-picker v-model="data.fromObj.begintime" type="date" style="width: 250px"
                value-format="YYYY-MM-DD" placeholder="请选择开始时间" />
            </el-form-item>
            <el-form-item label="结束时间:" prop="endtime">
              <el-date-picker v-model="data.fromObj.endtime" type="date" style="width: 250px" value-format="YYYY-MM-DD"
                placeholder="请选择结束时间" />
            </el-form-item>
            <el-form-item label="值班要求:">
              <el-input v-model="data.fromObj.ondutyrequire" autosize type="textarea" clearable maxlength="200"
                style="width: 715px" />
            </el-form-item>
            <el-form-item label="附件上传：">
              <MOSTY.Upload :widthNumber="800" v-model="data.fromObj.file" :limit="1" :delrow="delrow" :showbut="true"
                @filehandleChange="changeFile" :ShowfileList="true" :isImg="false" :showinput="true"
                :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'xls', 'xlsx', 'wps']" :disabled='!props.saveBtnShow' />
            </el-form-item>
          </el-form>
        </div>

        <MOSTY.Assort :title="'值班人员信息'" />
        <div style="margin-bottom: 10px" v-if="props.saveBtnShow">
          <el-button @click="addInfo"><el-icon size="small">
              <Plus />
            </el-icon>新增</el-button>
        </div>
        <div class="tabbox">
          <el-table :data="data.fromObj.tbOndutymanagesonList" border stripe style="width: 100%" :height="tableHeight"
            :key="keyCount" @current-change="handleCurrentChange">
            <el-table-column sortable prop="ondutytime" align="center" label="值班日期"></el-table-column>
            <el-table-column sortable prop="leadname" label="值班领导">
            </el-table-column>
            <el-table-column sortable prop="dutyofficername" align="center" label="值班负责人"></el-table-column>
            <el-table-column sortable prop="supervisepeoplename" align="center" label="督察人员">
            </el-table-column>
            <el-table-column sortable prop="drivername" align="center" label="驾驶员">
            </el-table-column>
            <el-table-column sortable prop="carplate" align="center" label="车辆"></el-table-column>
            <el-table-column sortable prop="ondutyphone" align="center" label="值班电话"></el-table-column>
            <el-table-column sortable prop="mobile" align="center" label="操作">
              <template #default="{ row }">
                <span style="color: rgb(8, 128, 184) !important;cursor: pointer;" @click="editInfo(row)"
                  v-if="props.saveBtnShow">编辑</span>
                <span style="color: rgb(8, 128, 184) !important;cursor: pointer;" @click="seeInfo(row)">查看</span>
                <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
                  @confirm="del(row)" v-if="props.saveBtnShow">
                  <template #reference>
                    <span class="operate" style="color: yellowgreen; margin-left: 5px;cursor: pointer;"
                      size="small">删除</span>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
      <template #footer>

        <el-button style="margin-left: 10px" type="primary" @click="handleSave(ruleFormRef)" v-if="props.saveBtnShow">
          <el-icon>
            <Search />
          </el-icon>
          <span>保存</span>
        </el-button>
        <el-button type="primary" @click="CloseEvent">
          <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span>
        </el-button>
      </template>
    </MOSTY.FromPage>
    <div class="right">

      <div class="box_cont">

        <!-- 详情 -->
        <el-dialog v-model="dialogVisible" :title="data.title" width="800px" :before-close="closeDialog">
          <div>
            <el-form class="mosty-from-wrap" ref="elform" label-width="110px" :model="data.tbOndutymanagesonList"
              :inline="true" :rules="rule2" style='width:716px !important;' :disabled="!savebtn">
              <el-form-item label="值班领导:" prop="leadname">
                <el-input v-model="data.tbOndutymanagesonList.leadname" @click="ChooesDdld('01')" clearable
                  style="width: 220px" />
              </el-form-item>
              <el-form-item label="值班时间:" prop="ondutytime">
                <el-date-picker v-model="data.tbOndutymanagesonList.ondutytime" type="date" style="width: 220px"
                  value-format="YYYY-MM-DD" placeholder="请选择值班时间" />
              </el-form-item>
              <el-form-item label="值班负责人:" prop="dutyofficername">
                <el-input v-model="data.tbOndutymanagesonList.dutyofficername" clearable @click="ChooesDdld('02')"
                  style="width: 220px" />
              </el-form-item>
              <el-form-item label="联系方式:" prop="dutyofficerphone">
                <MOSTY.Phone width="220px" show-word-limit v-model="data.tbOndutymanagesonList.dutyofficerphone"
                  maxlength="11" clearable @onInput="phoneChange">
                </MOSTY.Phone>
              </el-form-item>
              <el-form-item label="值班人员:" prop="ondutypeoplename">
                <el-input v-model="data.tbOndutymanagesonList.ondutypeoplename" type="textarea" clearable
                  style="width: 545px" />
                <el-button type="primary" @click="ChooesDdld('04')">选择</el-button>
              </el-form-item>
              <el-form-item label="督查人:">
                <el-input v-model="data.tbOndutymanagesonList.supervisepeoplename" @click="ChooesDdld('03')" clearable
                  style="width: 220px" />
              </el-form-item>
              <el-form-item label="值班联系方式:" prop="ondutypeoplephone">
                <MOSTY.Phone width="220px" show-word-limit v-model="data.tbOndutymanagesonList.ondutypeoplephone"
                  maxlength="11" clearable @onInput="phoneChange">
                </MOSTY.Phone>
              </el-form-item>
              <el-form-item label="值班车辆:">
                <el-select v-model="data.tbOndutymanagesonList.carplate" @change="cahngecsmc" clearable
                  placeholder="请选择值班车辆：" style="width: 220px">
                  <el-option v-for="item in carlist" :key="item.carid" :label="item.car" :value="item.carid" />
                </el-select>
              </el-form-item>
              <el-form-item label="驾驶员:">
                <el-select v-model="data.tbOndutymanagesonList.drivername" @change="cahngedriver" clearable
                  placeholder="请选择驾驶员：" style="width: 220px">
                  <el-option v-for="item in driverlist" :key="item.driveruserid" :label="item.drivername"
                    :value="item.driveruserid" />
                </el-select>
              </el-form-item>
              <el-form-item label="值班电话:" prop="ondutyphone">
                <MOSTY.Phone width="220px" show-word-limit v-model="data.tbOndutymanagesonList.ondutyphone"
                  maxlength="11" clearable @onInput="phoneChange">
                </MOSTY.Phone>

              </el-form-item>
              <el-form-item label="备注:">
                <el-input v-model="data.tbOndutymanagesonList.bz" autosize type="textarea" clearable maxlength="200"
                  style='width:600px;' />
              </el-form-item>
            </el-form>
          </div>
          <template #footer>
            <span class="dialog-footer">

              <el-button v-if='savebtn' @click="saveinfo(elform)">
                <el-icon>
                  <DocumentChecked />
                </el-icon>保存
              </el-button>
              <el-button @click="closeDialog">
                <el-icon>
                  <DocumentDelete />
                </el-icon>关闭
              </el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>
    <!-- 选择带队领导 -->
    <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="memberList" :deptId="deptId"
      :leaderid="leaderid" @choosedUsers="getSonValue"></ChooseUser>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  defineProps,
  defineEmits,
  reactive,
  watch,
  watchEffect,
  getCurrentInstance
} from "vue";
import { getItem } from "@/utils/storage";
import * as MOSTY from "@/components/MyComponents/index";
import { ElMessage } from "element-plus";
import * as rule from "@/utils/rules.js";
import { createAndClickLink } from "@/utils/tools.js";
import { getApi, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
const { proxy } = getCurrentInstance();
const { D_BZ_SBSSZT, D_BZ_WPDW, D_TB_JCBZLB, D_BZ_JXSBLX, D_BZ_JCZT } =
  proxy.$dict(
    "D_BZ_SBSSZT",
    "D_BZ_WPDW",
    "D_TB_JCBZLB",
    "D_BZ_JXSBLX",
    "D_BZ_JCZT"
  );
const props = defineProps({
  editObj: {
    type: Object,
    default: () => { }
  },
  title: String,
  saveBtnShow: {
    default: true,
    type: Boolean
  }
});
const savebtn = ref(true)
const rules = reactive({
  ondutyname: [
    { required: true, message: "值班名称不能为空", trigger: "blur" }
  ],
  ondutysite: [
    { required: true, message: "值班地点不能为空", trigger: "blur" }
  ],
  begintime: [{ required: true, message: "开始时间不能为空", trigger: "blur" }],
  endtime: [{ required: true, message: "结束时间不能为空", trigger: "blur" }]
});
const rule2 = reactive({
  ...rule.phoneRule({
    require: false,
    validator: true
  }, 'dutyofficerphone'),
  ...rule.phoneRule({
    require: false,
    validator: true
  }, 'ondutypeoplephone'),
  ...rule.phoneRule({
    require: false,
    validator: true
  }, 'ondutyphone'),

  leadname: [
    { required: true, message: "值班领导不能为空", trigger: "blur" }
  ],
  ondutytime: [
    { required: true, message: "值班时间不能为空", trigger: "blur" }
  ],
  dutyofficername: [{ required: true, message: "值班负责人不能为空", trigger: "blur" }],
  ondutypeoplename: [{ required: true, message: "值班人员不能为空", trigger: "blur" }]
});
const activeNames = ref(1);
const elform = ref(null)
const emits = defineEmits(["close"]);
const dialogVisible = ref(false);
const chooseUserVisible = ref(false); //选择领导弹窗
const singleShow = ref(true); //单选多选
const leaderid = ref("");
const memberList = ref([]); //成员选择的id回显
const zzlx = ref(null);
const data = reactive({
  fromObj: {},
  tbOndutymanagesonList: {}
});
const deptId = ref("");
const fjidlist = reactive({});
const delrow = ref({}); //删除文件列表
const fjtableData = ref([]);
const carlist = ref([])
const driverlist = ref([])
onMounted(() => {
  activeNames.value = ["1", "2", "3"];
  getcarlist()
  getdriverlist()
});
//获取车辆数据、
function getcarlist() {
  getApi({}, '/mosty-jcgl/car/getCarByPerson').then(res => {
    carlist.value = res
  })
}
function closeDialog(params) {
  if (savebtn.value) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        dialogVisible.value = false
      })
      .catch(() => {
        // catch error
      })
  } else {
    dialogVisible.value = false
  }

}
//获取车辆选择
const cahngecsmc = (val) => {
  carlist.value.forEach((item) => {
    if (item.carid == val) {
      data.tbOndutymanagesonList.carplate = item.car;
      data.tbOndutymanagesonList.carid = item.carid;
      data.tbOndutymanagesonList.drivername = item.drivername
      data.tbOndutymanagesonList.driveruserid = item.driverid
    }
  });
};
//获取驾驶员数据
function getdriverlist() {
  getApi({}, '/mosty-jcgl/driver/getDriverByOrg').then(res => {
    driverlist.value = res
  })
}
const cahngedriver = (val) => {
  driverlist.value.forEach((item) => {
    if (item.driveruserid == val) {
      data.tbOndutymanagesonList.drivername = item.drivername
      data.tbOndutymanagesonList.driveruserid = item.driveruserid
    }
  });
};
// 新的文件上传返回
const changeFile = (data) => {
  if (data.length > 0 && data[0].response) {
    let arr = data.map((e) => {
      return e.raw;
    });
    fjtableData.value = arr;
  } else {
    fjtableData.value = data;
  }
};
//点击下载文件
function handledlon(val) {
  createAndClickLink(val.url, val.name)
}
//删除文件
const realFileslistdelete = (row) => {
  delrow.value = row;
  fjtableData.value = fjtableData.value.filter((item) => {
    return item != row;
  });
};
//新增
function addInfo() {
  data.title = "人员信息新增";
  savebtn.value = true;
  data.tbOndutymanagesonList = {};
  dialogVisible.value = true;
}
//编辑
function editInfo(row) {
  data.tbOndutymanagesonList = row;
  savebtn.value = true;
  data.title = "人员信息编辑";
  dialogVisible.value = true;
}
//编辑
function seeInfo(row) {
  data.tbOndutymanagesonList = row;
  savebtn.value = false;
  data.title = "人员信息详情";
  dialogVisible.value = true;
}
//保存
const saveinfo = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (data.title == "人员信息新增") {
        let arr = [];
        arr.push(data.tbOndutymanagesonList);
        data.fromObj.tbOndutymanagesonList = arr;
        dialogVisible.value = false;
      }
      if (data.title == "人员信息编辑") {
        data.fromObj.tbOndutymanagesonList.forEach((item) => {
          if (item.id == data.tbOndutymanagesonList.id) {
            item = data.tbOndutymanagesonList;
          }
        });
        dialogVisible.value = false;
      }
    } else {
      ElMessage.warning('请输入必填项！！！')
    }
  })
}

const del = (row) => {
  data.fromObj.tbOndutymanagesonList =
    data.fromObj.tbOndutymanagesonList.filter((item) => {
      return item != row;
    });
};
const CloseEvent = () => {
  if (props.saveBtnShow) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        // 关闭上一次的表单校验
        ruleFormRef.value.clearValidate();
        emits("close");
      })
      .catch(() => {
        // catch error
      })
  } else {
    // 关闭上一次的表单校验
    ruleFormRef.value.clearValidate();
    emits("close");
  }

};

function ChooesDdld(val) {
  zzlx.value = val;
  if (val == "01" || val == "02" || val == "03") {
    leaderid.value = "";
    if (val == "01") {
      leaderid.value = data.tbOndutymanagesonList.leadid;
    }
    if (val == "02") {
      leaderid.value = data.tbOndutymanagesonList.dutyofficerid;
    }
    if (val == "03") {
      leaderid.value = data.tbOndutymanagesonList.supervisepeopleid;
    }

    singleShow.value = true;
    chooseUserVisible.value = true;
  } else {
    // 成员list用作表格回显
    if (val == "04" && data.tbOndutymanagesonList.ondutypeoplenameList) {
      memberList.value = data.tbOndutymanagesonList.ondutypeoplenameList.map(
        (item) => {
          return item.ondutypeopleid;
        }
      );
    }
    chooseUserVisible.value = true;
    singleShow.value = false;
  }
}
const getSonValue = (value) => {
  if (zzlx.value == "01") {
    data.tbOndutymanagesonList.leadname = value[0].userName;
    data.tbOndutymanagesonList.leadid = value[0].id;
  } else if (zzlx.value == "02") {
    data.tbOndutymanagesonList.dutyofficername = value[0].userName;
    data.tbOndutymanagesonList.dutyofficerid = value[0].id;
  } else if (zzlx.value == "03") {
    data.tbOndutymanagesonList.supervisepeoplename = value[0].userName;
    data.tbOndutymanagesonList.supervisepeopleid = value[0].id;
  } else if (zzlx.value == "04") {
    let arr = [];
    let arrid = [];
    for (let i = 0; i < value.length; i++) {
      const element = value[i];
      element.zzlx = zzlx.value;
      arr.push(element.userName);
      arrid.push(element.id);
    }
    memberList.value = value.map((item) => {
      return item.id;
    });
    data.tbOndutymanagesonList.ondutypeoplenameList = value.map((item) => {
      return {
        ondutypeopleid: item.id,
        ondutypeoplename: item.userName
      };
    });
    data.tbOndutymanagesonList.ondutypeoplename = arr.toString();
    data.tbOndutymanagesonList.ondutypeopleid = arrid.toString();
  }
};
const ruleFormRef = ref();
const handleSave = async (ruleFormRef) => {
  if (!ruleFormRef) return;
  await ruleFormRef.validate((valid) => {
    if (valid) {
      data.fromObj.tbOndutymanagesonList = data.fromObj.tbOndutymanagesonList
        ? data.fromObj.tbOndutymanagesonList
        : [];
      data.fromObj.file = data.fromObj.file ? data.fromObj.file.toString() : "";
      if (data.fromObj) {
        if (props.title == "值班管理新增") {
          postApi(data.fromObj, "/mosty-jcgl/ondutymanage/addOndutymanageOne")
            .then((res) => {
              ElMessage.success("新增成功");
              emits("close");
            })

        } else if (props.title == "值班管理修改") {
          postApi(
            data.fromObj,
            "/mosty-jcgl/ondutymanage/updateOndutymanageOne"
          )
            .then((res) => {
              ElMessage.success("修改成功");
              emits("close");
            })

        }
      }
    } else {
      ElMessage.error("请输入必填项");
    }
  });
};
watchEffect(() => {
  if (props.editObj) {
    data.fromObj = props.editObj;
  } else {
    data.fromObj = {};
  }
});
</script>

<style lang="scss" scoped>
.box_cont {
  height: calc(100vh - 10vh);
  overflow-y: scroll;
}

.searchBox {
  width: 1333px;
  margin: 20px auto;
}

.ld_box {
  display: flex;
  margin-right: 30px;
}

.el-form {
  width: 847px;
  align-items: center;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin: auto;
}

.el-form-item {
  display: flex;
  margin-right: 0px;
}

.addbtn {
  margin-bottom: 10px;
}

.bigBox {
  display: block !important;
  padding: 0 14px;
  box-sizing: border-box;
}

.tabbox {
  max-height: 300px;
  overflow-y: scroll;

  .input {
    width: 100%;
    height: 100%;
  }
}

::v-deep .el-table .cell {
  padding: 0 0 !important;
}

::v-deep .el-table--border .el-table__cell .cell {
  padding-left: 0px !important;

  >input {
    width: 100%;
    height: 33px;
  }
}

::v-deep .el-upload-list {
  width: 50%;
}
</style>