<template>
  <div style="padding-top: 13vw">
    <TopNav :navTitle="title" />
    <van-form @submit="onSubmit" style="height: calc(100vh - 13vw);">
      <div class="infoBox">
        <ul class="cardInfo">
          <li class="item">
            <van-field v-model="normalForm.dwlxmc" required name="单位类型" label="单位类型" :disabled="disabled"
              placeholder="请选择单位类型" input-align="right" readonly is-link
              :rules="[{ required: true, message: '请选择单位类型' }]" @click="getCommonPop('dwlx')" />
          </li>
          <li class="item">
            <van-field v-model="normalForm.dwmc" required name="单位名称" label="单位名称" :disabled="disabled"
              placeholder="请输入单位名称" input-align="right" :rules="[{ required: true, message: '请输入单位名称' }]" />
          </li>
          <li class="item">
            <van-field v-model="normalForm.dwflmc" required name="单位分类" label="单位分类" is-link :disabled="disabled"
              placeholder="请选择单位分类" input-align="right" readonly :rules="[{ required: true, message: '请选择单位分类' }]"
              @click="getCommonPop('dwfl')" />
          </li>

          <li class="item">
            <van-field v-model="normalForm.lxdh" required :disabled="disabled" name="联系电话" label="联系电话"
              placeholder="请输入联系电话" input-align="right" :rules="[{ required: true, message: '请输入联系电话' }]" />
          </li>

          <li class="item">
            <van-field v-model="normalForm.dws" required :disabled="disabled" name="单位数" label="单位数"
              placeholder="请输入单位数" input-align="right" type="digit" :rules="[{ required: true, message: '请输入单位数' }]" />
          </li>
          <li class="item">
            <van-field v-model="normalForm.addreess" required :disabled="disabled" name="地址" label="地址" readonly />
            <div @click="addDz"><van-icon name="location" color="#4788e1" size="6vw" /></div>
          </li>
          <ul>
            <li class="item-li" v-for="(it, idx) in dzList" :key="idx">
              <span class="text">地址{{ idx + 1 }}：</span>
              <span class="info"><van-field v-model="it.dz" /></span>
              <span @click="deletItem('dz', idx)" class="iconClose"><van-icon name="close" color="red" size="6vw" /></span>
            </li>
          </ul>
          <li class="item">
            <van-field v-model="normalForm.addreess" required :disabled="disabled" name="从业人员" label="从业人员" readonly />
            <div @click="showDialogfn('cyry')"><van-icon name="add-o" color="#4788e1" size="6vw" /></div>
          </li>
          <ul>
            <li class="item-li" v-for="(it, idx) in dataList.ryList" :key="idx">
              <span class="text">人员：</span>
              <span class="info"><van-field readonly v-model="it.info" /></span>
              <span @click="deletItem('ry', idx)" class="iconClose"><van-icon name="close" color="red" size="6vw" /></span>
            </li>
          </ul>
          <li class="item">
            <van-field name="备注" readonly label="备注" />
          </li>
          <div class="textarea">
            <van-field placeholder="请输备注" v-model="normalForm.bz" :disabled="disabled" rows="4" autosize maxlength="500" show-word-limit type="textarea"></van-field>
          </div>
        </ul>
        <div class="footer">
          <van-button round block type="primary" native-type="submit" :loading="isLoading" loading-type="spinner" loading-text="登录中...">提交</van-button>
        </div>
      </div>
    </van-form>
  </div>

  <!-- 弹窗 -->
  <van-popup v-model:show="isShowCommonPicker" round position="bottom">
    <van-picker v-if="clickType == 'dwlx' || clickType == 'dwfl'" :columns="columns"
      @cancel="isShowCommonPicker = false" @confirm="onConfirm" />
  </van-popup>
  <!-- 弹窗 -->
  <Select v-if="showSelect" :checked="r_checked" :selectType="selectType" :show="showSelect"
    :checkedList="hasCheckedList" @update:cancel="showSelect = false" @update:confirm="onComfirm" :key="selectIndex" />
</template>
<script setup>
import Select from "./components/Select.vue";
import { dwglDetail, editDwgl, addDwgl } from "../../../api/xfgl.js";
import { useRouter, useRoute } from "vue-router";
import TopNav from "../../../components/topNav.vue";
import { hintToast, timeValidate } from "../../../utils/tools";
import { getDictList, setDict } from "../../../utils/dict";
import { ref, onMounted, reactive, defineProps } from "vue";
const { D_BZ_DWLX, D_BZ_DWFL } = getDictList("D_BZ_DWLX", "D_BZ_DWFL");
const route = useRoute();
const router = useRouter();
const message = ref("");
const normalForm = ref({
  ssbmdm: JSON.parse(window.localStorage.getItem("userInfo")).deptList[0].deptCode
});
const columns = ref([]);
const isLoading = ref(false);
const disabled = ref(false)
const isShowCommonPicker = ref(false);
const clickType = ref(""); //点击选择
const showSelect = ref(false);
const r_checked = ref(""); //选择的类型
const hasCheckedList = ref([]); //选择的类型
const selectIndex = ref(1); //选择器组件KEY
const title = ref("新增单位");
const dzList = ref([])
const selectType = ref('')
const dataList = reactive({
  ryList: [], //人员
});
onMounted(() => {
  title.value = route.query.id ? "编辑单位" : "新增单位";
  // disabled.value = route.query.id ? true : false;
  if (route.query.id) _getDetailById(); //根据id获取详情
});
//根据id获取详情
function _getDetailById() {
  dwglDetail(route.query.id).then((res) => {
    normalForm.value = res;
    D_BZ_DWLX.value.forEach((element) => {
      if (element.dm == res.dwlx) normalForm.value.dwlxmc = element.text;
    });
    D_BZ_DWFL.value.forEach((element) => {
      if (element.dm == res.dwfl) normalForm.value.dwflmc = element.text;
    });
    let list = res.cyry ? JSON.parse(res.cyry) : []
    dataList.ryList = list.map(item => {
      if (!item.info) item.xm + '(' + item.sfzh + ')'
      return item
    })
    hasCheckedList.value = dataList.ryList.map((item) => {
      return item.key;
    });
    dzList.value = []
    for (let key in res) {
      if (key.search('dz') != -1) dzList.value.push({ dz: res[key] });
    }
  });
}
// 新增地址
function addDz() {
  if (disabled.value) return false;
  dzList.value.push({ dz: '' })
}
// 打开弹窗
function showDialogfn(type) {
  if (disabled.value) return false;
  selectType.value = type; //选取的类型
  showSelect.value = true; //打开弹窗
  hasCheckedList.value = [];
  r_checked.value = "";
  selectIndex.value++;
  hasChooseData();
}
// 已经选取的数据回显
function hasChooseData() {
  switch (selectType.value) {
    case "cyry":
      if (!dataList.ryList.length) return false;
      hasCheckedList.value = dataList.ryList.map((item) => {
        return item.key;
      });
      break;
  }
}

//确认选择
function onComfirm(val) {
  if (val.length <= 0) return false;
  switch (selectType.value) {
    case "cyry":
      dataList.ryList = val.map(v => {
        v.info = v.xm + '(' + v.sfzh + ')'
        return v
      }); //选取的组员
      normalForm.value.cyry = JSON.stringify(val)
      break;
  }
}

// 选择
function getCommonPop(val) {
  if (disabled.value) return false;
  clickType.value = val;
  switch (val) {
    case "dwlx":
      columns.value = D_BZ_DWLX.value;
      break;
    case "dwfl":
      columns.value = D_BZ_DWFL.value;
      break;
  }
  isShowCommonPicker.value = true;
}
// 确定选择
function onConfirm(val) {
  isShowCommonPicker.value = false;
  switch (clickType.value) {
    case "dwlx":
      normalForm.value.dwlxmc = val.text;
      normalForm.value.dwlx = val.dm;
      break;
    case "dwfl":
      normalForm.value.dwflmc = val.text;
      normalForm.value.dwfl = val.dm;
      break;
  }
}

// 删除选择的人员-地址
function deletItem(type, index) {
  if (disabled.value) return false;
  switch (type) {
    case 'dz':
      dzList.value.splice(index, 1)
      break;
    case 'cyry':
      dataList.ryList.splice(index, 1);
      hasCheckedList.value = dataList.ryList.map((item) => {
        return item.key;
      });
      normalForm.value.cyry = JSON.stringify(dataList.ryList)
      break;
  }
}

// 提交
function onSubmit() {
  let pramas = {
    ...normalForm.value
  }
  dzList.value.forEach((item, idex) => {
    if (idex > 0) {
      pramas['dz' + idex] = item.dz
    } else {
      pramas['dz'] = item.dz
    }
  })
  isLoading.value = true;
  if (title.value == '编辑单位') {
    editDwgl(pramas).then(res => {
      hintToast('编辑成功')
      router.push({ path: "/Declaration" });
    })
  } else {
    addDwgl(pramas).then(res => {
      hintToast('新增成功')
      router.push({ path: "/Declaration" });
    })
  }
}
</script>
<style lang="less" scoped>
.infoBox {
  height: 100%;
  position: relative;

  .cardInfo {
    height: calc(100vh - 13vw);
    padding: 1vw 4vw;
    box-sizing: border-box;
    overflow: hidden;
    overflow-y: auto;

    .item {
      position: relative;
      display: flex;
      justify-content: space-between;
      align-items: center;
      // height: 8vw;
      width: 100%;
      border-bottom: 1px solid #e5e5e5;

      .mark {
        margin: 0 10px;
        color: red;
        font-size: 16px;
      }

      .text {
        color: #767676;
      }
    }

    .item::before {
      position: absolute;
      content: "";
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      background: #0066ff;
      width: 2px;
      height: 12px;
      z-index: 11;
    }
  }

  .footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 60px;
    text-align: center;

    .btn {
      padding: 2vw 6vw;
      background: #1989fa;
      color: #fff;
      border-radius: 4px;
    }
  }
}

.item-li {
  display: flex;
  justify-content: space-between;
  padding: 2vw 4vw;
  box-sizing: border-box;

  .info {
    margin: 0 10px;
    flex: 1;

    ::v-deep .van-cell__value {
      background: #e5eff5;
      padding-left: 10px;
      box-sizing: border-box;
    }

    ::v-deep .van-cell {
      padding: 0;
    }
  }

  .text {
    color: #8b8b94;
    width: 16vw;
  }

  .iconClose {
    display: inline-block;
    width: 6vw;
  }

}

.textarea {
  ::v-deep .van-field__control {
    background: #f8fafd;
    padding-left: 4px;
  }
}
</style>