<template>
  <div class="dialog" v-if="isShowDialog">
    <div class="head_box">
      <span class="title" v-if="!isDetail">{{ isAdd ? '新增' : '修改' }}</span>
      <span class="title" v-else>详情</span>
      <div>
        <el-button type="primary" size="small" @click="onSave" :loading="buttonLoading" v-if="!isDetail">保存</el-button>
        <el-button size="small" @click="closeDialog">关闭</el-button>
      </div>
    </div>
    <div class="form-content">
      <el-form ref="formRef" :label-width="140" :model="formData" :rules="rules" inline>
        <div class="content">
          <el-form-item style="width:48%" class="form-item" prop="faMc" label="方案名称">
            <el-input v-model="formData.faMc" :disabled="isDetail" placeholder="请输入方案名称"></el-input>
          </el-form-item>
          <el-form-item style="width:48%" class="form-item" prop="faBmdj" label="方案部门等级">
            <MOSTY.Select :dictEnum="props.dic.D_QW_FA_BMDJ" :disabled="isDetail" placeholder="请选择方案部门等级"
              v-model="formData.faBmdj" />
          </el-form-item>
          <el-form-item style="width:48%" class="form-item" prop="faQwdj" label="方案勤务等级">
            <MOSTY.Select :dictEnum="props.dic.D_QW_FA_QWDJ" :disabled="isDetail" placeholder="请选择方案勤务等级"
              v-model="formData.faQwdj" />
          </el-form-item>

          <el-form-item style="width:48%" class="form-item" prop="faSjKsrq" label="方案时间开始日期">
            <el-date-picker style="width:100%;" type="date" v-model="formData.faSjKsrq" :disabled="isDetail"
              value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item style="width:48%" class="form-item" prop="faSjJsrq" label="方案时间结束日期">
            <el-date-picker style="width:100%;" type="date" v-model="formData.faSjJsrq" :disabled="isDetail"
              value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item style="width:48%" class="form-item" prop="bbsl" label="报备数量">
            <el-input-number v-model="formData.bbsl" :disabled="isDetail" :min="0" :step="1"></el-input-number>
          </el-form-item>
          <!-- 这里要改列表 -->
          <el-form-item style="width:48%" v-if="!isDetail" class="form-item" prop="bmListVal" label="部门列表">
            <!-- <MOSTY.Department width="100%" clearable @getDepValue="modelValue" multiple v-model="formData.bmListVal" :modelValue="formData.bmListVal" :noLazyTree="true" /> -->
            <!-- <Department width="100%" clearable @getDepValue="modelValue"
             multiple v-model="formData.bmListVal"
              :modelValue="formData.bmListVal" noLazyTree /> -->
                 <MOSTY.Department :multiple="true"  width="100%"
              clearable noLazyTree @getDepValue="getDepValue"
              v-model="formData.bmListVal"
            />
          </el-form-item>
          <el-form-item prop="kdbbs" label="环林卡口" style="width: 48%">
            <div class="inputbox" @click="chooseUserVisible = true">
              <el-tag v-for="(item, index) in listData.jczList" :key="index" class="mx-1" closable
                @close="handleCloseCl(item)">
                {{ item.jczmc }}
              </el-tag>
            </div>
          </el-form-item>
          <el-form-item prop="kdbbs" label="警务站" style="width: 48%">
            <div class="inputbox" @click="JwzLoadVisible = true">
              <el-tag v-for="(item, index) in listData.jwzList" :key="index" class="mx-1" closable
                @close="JwzCloseCl(item)">
                {{ item.jwzMc }}
              </el-tag>
            </div>
          </el-form-item>
          <el-form-item prop="kdbbs" label="专家库" style="width: 48%">
            <div class="inputbox" @click="ZjkLoadVisible = true">
              <el-tag v-for="(item, index) in listData.zjkList" :key="index" class="mx-1" closable
                @close="ZjkCloseCl(item)">
                {{ item.xm }}
              </el-tag>
            </div>
          </el-form-item>
          <el-form-item prop="kdbbs" label="资源库" style="width: 48%">
            <div class="inputbox" @click="ZykLoadVisible = true">
              <el-tag v-for="(item, index) in listData.zykList" :key="index" class="mx-1" closable
                @close="ZykCloseCl(item)">
                {{ item.zymc }}
              </el-tag>
            </div>
          </el-form-item>
          <el-form-item prop="kdbbs" label="法律指引" style="width: 48%">
            <div class="inputbox" @click="FlLoadVisible = true">
              <el-tag v-for="(item, index) in listData.flzyList" :key="index" class="mx-1" closable
                @close="ZykCloseCl(item)">
                {{ item.title }}
              </el-tag>
            </div>
          </el-form-item>
          <el-form-item style="width:100%" class="form-item" prop="faSm" label="方案说明">
            <el-input type="textarea" v-model="formData.faSm" :disabled="isDetail" placeholder="请输入方案说明"></el-input>
          </el-form-item>
          <el-form-item style="width:100%" class="form-item" prop="faZl" label="方案资料">
            <el-input type="textarea" v-model="formData.faZl" :disabled="isDetail" placeholder="请输入方案资料"></el-input>
          </el-form-item>

        </div>
        <div v-if="isDetail" class="department-list">
          <h3>部门列表:</h3>
          <div class="department-item" v-for="item of formData.bmList" :key="item.id">
            {{ item.ssbm }}
          </div>
        </div>
      </el-form>
    </div>

  </div>
  <JczLoad v-model="chooseUserVisible" @choosedJcz="choosedJcz" :modelValue='true' :data='listData.jczList' />
  <ZjkLoad v-model="ZjkLoadVisible" @choosedJcz="choosedZjk" :modelValue='true' :data='listData.zjkList' />
  <JwzLoad v-model="JwzLoadVisible" @choosedJcz="choosedJwz" :modelValue='true' :data='listData.zjkList' />
  <ZykLoad v-model="ZykLoadVisible" @choosedJcz="choosedZyk" :modelValue='true' :data='listData.zykList' />
  <FlLoad v-model="FlLoadVisible" @choosedJcz="choosedFl" :modelValue='true' :data='listData.flzyList' />
</template>

<script setup>
import{qwfaUpdate,qwfaSave} from '@/api/lzqwzx/index.js'
import { reactive, ref, getCurrentInstance, defineEmits } from "vue";
import JczLoad from "@/components/DanLoding/jczLoad.vue";
import ZjkLoad from "@/components/DanLoding/ZjkLoad.vue";
import JwzLoad from "@/components/DanLoding/jwzLoad.vue";
import ZykLoad from "@/components/DanLoding/zykLoad.vue";
import FlLoad from "@/components/DanLoding/flLoad.vue";
import * as MOSTY from "@/components/MyComponents/index";
import * as rule from "@/utils/rules.js";
import { qwfatbQwglQwfa } from '@/api/file.js'
import Department from "./department.vue";

const { proxy } = getCurrentInstance();
const { D_BZ_SF } = proxy.$dict("D_BZ_SF");
const props = defineProps({
  dic: Object
});

const emits = defineEmits(["updateList"]);
const loading = ref(false); // 加载
const formRef = ref(); // 表单验证
const formDataDefault = ref({});
const formData = ref({});
const title = ref("");
let listData = reactive({
  jczList: [],
  jwzList: [],
  zjkList: [],
  zykList: [],
  flzyList: []
});
formData.value.bmList = [];

/** type {Array} 部门列表 */
const modelValue = (val) => {
  console.log("val", val);
  if (val?.length > 0) {
    formData.value.bmList = val.map((item) => {
      const isTrue = D_BZ_SF.value[1]?.dm;
      const isFalse = D_BZ_SF.value[0]?.dm;
      return {
        isChild: isTrue,
        ssbm: item.orgName,
        ssbmdm: item.orgCode
      };
    });
  } else {
    formData.value.bmList = [];
  }
};
const isAdd = ref(false); // 是否是新增状态
const isShowDialog = ref(false); //弹窗
const dialogType = ref(0); // add 新增 edit编辑 detail详情
const isDetail = ref(false);
const rules = reactive({
  faMc: [{ required: true, message: "请填写方案名称", trigger: "blur" }],
  faBmdj: [{ required: true, message: "请选择部门等级", trigger: "blur" }],
  faQwdj: [{ required: true, message: "请选择勤务等级", trigger: "blur" }],
  faSjKsrq: [
    { required: true, message: "请选择方案时间开始日期", trigger: "blur" }
  ],
  faSjJsrq: [
    { required: true, message: "请选择方案时间结束日期称", trigger: "blur" }
  ]
});
/**部门id对照对象 */
let departmentIdObj = {};
const init = (type, row) => {
  //   formDataDefault.value = JSON.parse(JSON.stringify(formData.value));
  isShowDialog.value = true; // 显示新增编辑dialog框
  isAdd.value = type == "add" ? true : false;
  dialogType.value = type;
  isDetail.value = type === "detail";
  // 是否有填充数据
  let data = formDataDefault.value || {};
  departmentIdObj = {};
  if (row && type == "edit") {
    // let {
    //   id,
    //   faMc,
    //   faBmdj,
    //   faQwdj,
    //   faSjKsrq,
    //   faSjJsrq,
    //   bmList,
    //   faSm,
    //   bbsl,
    //   faZl
    // } = row;

    /** 初始化-获取需要的部门列表格式 */
    const getNeedBmList = (arr) => {
      if (!Array.isArray(arr)) return [];
      return arr.map((item) => {
        let newItem = {
          isChild: item?.isChild,
          ssbm: item?.ssbm,
          ssbmdm: item?.ssbmdm
        };
        return newItem;
      });
    };
    /**保存一份原来部门列表的id在对象中 */
    function getDepartmentIdObj(arr) {
      let obj = {};
      if (!Array.isArray(arr)) return {};
      arr.forEach((item) => {
        let code = item.ssbmdm; // 部门代码 ssbmdm
        obj[code] = item.id;
      });
      return obj;
    }

    // formData.value = {
    //   id,
    //   faMc,
    //   faBmdj,
    //   faQwdj,
    //   faSjKsrq,
    //   faSjJsrq,
    //   bmList,
    //   bmListVal,
    //   faSm,
    //   bbsl,
    //   faZl
    // };
    // 新增
    qwfatbQwglQwfa(row.id).then(res => {
      formData.value = res
      departmentIdObj = getDepartmentIdObj(res.bmList);
      formData.value.bmList = getNeedBmList(res.bmList);
      formData.value.bmListVal = res.bmList.map((item) => item.ssbmdm);
      listData.jczList = res.jczList
      listData.jwzList = res.jwzList
      listData.zjkList = res.zjkList
      listData.zykList = res.zykList
      listData.flzyList = res.flzyList
    })
  } else if (type == "detail") {
    qwfatbQwglQwfa(row.id).then(res => {
      formData.value = res
      listData.jczList = res.jczList
      listData.jwzList = res.jwzList
      listData.zjkList = res.zjkList
      listData.zykList = res.zykList
      listData.flzyList = res.flzyList
    })
  }
};

// 重置表单
const reserForm = () => {
  formData.value = JSON.parse(JSON.stringify(formDataDefault.value));
};
// 关闭弹窗
const closeDialog = () => {
  isShowDialog.value = false;
  loading.value = false;
  listData.jczList = []
      listData.jwzList = []
      listData.zjkList = []
      listData.zykList = []
      listData.flzyList = []
  formData.value = JSON.parse(JSON.stringify(formDataDefault.value));
};
/**获取有id的部门列表(原来有的就赋值上去,否则为空) */
const getBmListWithId = (arr) => {
  if (!Array.isArray(arr)) return [];
  return arr.map((item) => {
    if (departmentIdObj[item.ssbmdm]) item.id = departmentIdObj[item.ssbmdm];
    return item;
  });
};
// 保持test TODO:
const onSave = () => {
  formRef.value.validate((valid) => {
    if (!valid) return;
    loading.value = true;
    buttonLoading.value = true;
    let params={}
if(formData.value.faMc.slice(-2)=='方案'){
  params= { ...formData.value, ...listData};
}else{
   params = { ...formData.value, ...listData,faMc:formData.value.faMc+'方案'};
}
let text = isAdd.value ? "新增成功" : "编辑成功";
    delete params.bmListVal;
    if (isAdd.value) {
      delete params.id;
  qwfaSave(params) .then((res) => {
        closeDialog();
        buttonLoading.value = false;
        proxy.$message.success(text);
        emits("updateList", {});
      })
      .catch(() => {
        loading.value = false;
        buttonLoading.value = false;
      });
    } else {
       params.bmList = getBmListWithId(params.bmList);
      qwfaUpdate(params) .then((res) => {
        closeDialog();
        buttonLoading.value = false;
        proxy.$message.success(text);
        emits("updateList", {});
      })
      .catch(() => {
        loading.value = false;
        buttonLoading.value = false;
      });
    }
    // let url = isAdd.value ? "/tbQwglQwfa/save" : "/tbQwglQwfa/update";

    if (isAdd.value) {

    } else {

    }
    // servicePost(params, `/mosty-qwzx${url}`)

  });
};
const buttonLoading = ref(false);

// 选择检查站
const chooseUserVisible = ref(false);
const choosedJcz = (row) => {
  listData.jczList = row;
  formData.value.kdbbs = row.length;
};
const handleCloseCl = (row) => {
  listData.jczList.splice(listData.jczList.indexOf(row), 1);
};
//选择检务站
const JwzLoadVisible = ref(false);
const choosedJwz = (row) => {
  listData.jwzList = row;
};
const JwzCloseCl = (row) => {
  listData.jwzList.splice(listData.jwzList.indexOf(row), 1);
};
//选择专家库
const ZjkLoadVisible = ref(false);
const choosedZjk = (row) => {
  listData.zjkList = row;
};
const ZjkCloseCl = (row) => {
  listData.zjkList.splice(listData.zjkList.indexOf(row), 1);
};
//选择资源库
const ZykLoadVisible = ref(false);
const choosedZyk = (row) => {
  listData.zykList = row;
};
const ZykCloseCl = (row) => {
  listData.zykList.splice(listData.zykList.indexOf(row), 1);
};
//法律指引
const FlLoadVisible = ref(false);
const FlCloseCl = (row) => {
  listData.flzyList.splice(listData.flzyList.indexOf(row), 1);
};
const choosedFl = (row) => {
  listData.flzyList = row;
};
const getDepValue = (res) => {
  formData.value.bmList = res.map(item => {
    return {
     ...item,
      ssbm: item.orgName,
      ssbmdm: item.orgCode
    }
  });
console.log(formData.value.bmList,"xxxxxxxxxxxxxxxxxxxxxxxxxx");

}
defineExpose({ init });
</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "~@/assets/css/element-plus.scss";

.form-content {
  margin-top: 20px;
}

.bblxItem {
  line-height: 40px;
  min-height: 40px;

  //   display: flex;
  .btItem {
    width: 180px;
    padding: 7px 0;
    background: #e9e9e9;
    color: #000;
    margin-top: 1px;
    text-align: center;
  }

  .info {
    flex: 1;
    background: #f2f2f2;
    margin-top: 1px;
    padding: 10px;
    box-sizing: border-box;
  }

  .subBtn {
    padding-left: 100px;
    box-sizing: border-box;
  }
}

.content {
  // display: flex;
  // flex-wrap: wrap;
  padding: 10px 40px;
}

.dialog {
  &::v-deep .el-form--inline {
    padding: 0 !important;
  }

  &::v-deep .el-input__inner {
    border: 1px solid #d5d2d2;
  }

  // width: ;
  //   overflow-x: hidden;
}

.dialog .el-form-item--default.form-item {
  // border: 1px solid rgb(226, 200, 200);
  // max-width: 400px;
  width: calc(50% - 100px);
  margin-bottom: 10px;
}

.department-list {
  padding: 10px 20px;
}

.department-item {
  color: #000;
  margin-left: 20px;
  height: 35px;
  line-height: 35px;
  // border-top: none;
}

.inputbox {
  width: 100%;
  min-height: 32px;
  border-radius: 5px;
  border: 1px solid #d5d2d2;
}
</style>
