<!--
 * @Author: your name
 * @Date: 2021-01-18 15:46:34
 * @LastEditTime: 2021-11-30 18:54:36
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue3-element-admin\src\views\Home.vue
-->
<template>
  <Bg></Bg>
  <Header></Header>
  <div class="container2">
    <div class="mainDiv">
      <div class="leftBox">
        <Title title="编辑农事"></Title>
        <div class="myForm">
          <div class="basis">
            <div class="basis-title">下发依据</div>
            <div class="basis-desc">
              您的果园2区、3区发现了花穗过长预警，飞鸟推荐疏花农事。
            </div>
          </div>
          <el-form
            :model="form"
            ref="formRef"
            :rules="rules"
            label-width="80px"
            :inline="false"
            class="form"
          >
            <el-form-item class="form-item" prop="nsTypeIds" label="农事类型">
              <el-select
                multiple
                @change="changeNsType"
                v-model="nsTypeIds"
                placeholder="请选择农事类型"
                effect="dark"
                popper-class="v-select-popper-ns"
              >
                <el-option
                  v-for="item in nsTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item class="form-item" prop="execStyle" label="执行方式">
              <el-radio-group fill="#13C4CD" v-model="execStyle">
                <el-radio-button :value="1" label="无人机"></el-radio-button>
                <el-radio-button :value="2" label="人工"></el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label-width="0" prop="drugList">
              <span>药物</span>
              <div class="table">
                <div class="thead">
                  <div class="th notopborder">功效</div>
                  <div class="th notopborder">类型</div>
                  <div class="th notopborder">药物配比/倍</div>
                  <div class="tools notopborder">增/删</div>
                </div>
                <div class="tbody">
                  <div v-for="(item, i) in drugList" :key="i" class="row">
                    <div class="col">
                      <select class="my-select" v-model="item.drugId">
                        <option class="my-option" label="请选择" value="" />
                        <option
                          class="option"
                          v-for="drug in nsDrugList"
                          :key="drug.id"
                          :label="drug.name"
                          :value="drug.id"
                        />
                      </select>
                    </div>
                    <div class="col">
                      <div class="prefix">1:</div>
                      <input
                        class="com"
                        v-model="item.peibi"
                        placeholder="输入配比"
                      />
                    </div>
                    <div class="col">
                      <input
                        class="com"
                        v-model="item.yongliang"
                        placeholder="输入用量"
                      />
                      <div class="prefix">ml/g</div>
                    </div>
                    <div class="tools">
                      <div
                        @click="addNsDrugItem()"
                        class="item-btn"
                        style="background-color: #3fb326"
                      >
                        +
                      </div>
                      <div @click="deleteItem(i)" class="item-btn">-</div>
                    </div>
                  </div>
                </div>
              </div>
            </el-form-item>
            <el-form-item class="form-item" prop="time2" label="执行范围">
              <el-select
                v-model="execRange"
                placeholder="请选择执行范围"
                popper-class="v-select-popper-ns"
                clearable
                effect="dark"
                style="width: 70%"
              >
                <el-option label="三天内" :value="3" />
              </el-select>
            </el-form-item>
            <el-form-item class="form-item" prop="time1" label="复核时间">
              <el-select
                v-model="reviewAfterDay"
                placeholder="请选择复核时间"
                popper-class="v-select-popper-ns"
                clearable
                effect="dark"
                style="width: 70%"
              >
                <!-- <el-option
                  v-for="item in options1"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                /> -->
                <el-option label="三天后" :value="3" />
              </el-select>
            </el-form-item>
            <el-form-item class="form-item" prop="desc" label="处方备注">
              <el-input
                v-model="desc"
                :rows="4"
                type="textarea"
                placeholder="请输入注意事项"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="my-bottoms">
          <!-- <el-button class="btn" type="warning" v-if="recordId" @click="initSettingVal" >重置</el-button> -->
          <el-button
            class="btn"
            color="rgba(255,78,0,.6)"
            @click="remove()"
            v-if="recordId"
            >删除</el-button
          >
          <el-button class="btn btn-size" color="#032C39">生成处方单</el-button>
          <el-button class="btn btn-size" color="#13C4CD" @click="onSubmit"
            >保存修改</el-button
          >
        </div>
      </div>

      <div class="rightBox">
        <div class="head">
          <div class="name">编辑执行区域</div>
          <div class="line"></div>
          <div class="rhombus"></div>
        </div>
        <div class="map" ref="mapRef">
          <YjTuli class="tuli"></YjTuli>
          <Tsyg @selectDay="selectDay" class="tsyj"></Tsyg>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useStore } from "vuex";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  onMounted,
  ref,
  reactive,
  toRefs,
  provide,
  inject,
  watch,
  computed,
} from "vue";
import config from "@/api/config.js";
import { NS_RECORD_STATUS_ENUM as STARUS_ENUM } from "../../api/enum";
import { useRoute, useRouter } from "vue-router";
import { dateFormat } from "../../utils/date_util";
import Title from "../components/title";
import EditNsMap from "./EditNsMap";
import Bg from "../Bg";
import Header from "@/views/components/Header.vue";
import YjTuli from "../znxy/com/YjTuli";
import Tsyg from "../znxy/com/Tsyg";

const emit = defineEmits(["back"]);
const selectDateObj = ref({});

const router = useRouter();
const route = useRoute();
const recordId = route.query.recordId;

const nsDrugList = ref([]);
const nsTypeList = ref([]);
const store = useStore();
const location = store.getters.userinfo.location;
const gardenId = store.getters.userinfo.curGardenId;
const mapRef = ref(null);
const form = reactive({
  gardenId,
  nsTypeIds: [],
  drugList: [{ drugId: "" }],
  treeIds: [],
  subAreaIds: [],
  execStyle: null,
  execRange: null,
  reviewAfterDay: null,
  desc: null,
  status: STARUS_ENUM.STAY_START,
});
const {
  nsTypeIds,
  drugList,
  execStyle,
  execRange,
  reviewAfterDay,
  desc,
  treeIds,
  subAreaIds,
} = toRefs(form);

const formRef = ref(null);

const rules = {
  execStyle: [
    {
      required: true,
      message: "请选择执行方式",
      trigger: "blur",
    },
  ],
  execRange: [
    {
      required: true,
      message: "请选择执行范围天数",
      trigger: "blur",
    },
  ],
  reviewAfterDay: [
    {
      required: true,
      message: "请选择复核时间",
      trigger: "blur",
    },
  ],
  nsTypeIds: [
    {
      required: true,
      message: "请选择农事类型",
      trigger: "blur",
    },
  ],
  treeIds: [
    {
      required: true,
      message: "请选择树",
      trigger: "blur",
    },
  ],
  subAreaIds: [
    {
      required: true,
      message: "请选择区",
      trigger: "blur",
    },
  ],
  drugList: [
    {
      required: true,
      message: "请添加农药/化肥",
      trigger: "blur",
    },
  ],
};

const options1 = [
  {
    value: "Option1",
    label: "三天后",
  },
];

const kmap = new EditNsMap();
onMounted(() => {
  initNsTypeList();
  kmap.initMap(location, mapRef.value);
  kmap.addToggleSubAreaSelect();
  kmap.addToggleTreeSelect();
  kmap.initArea(gardenId, () => {});
  kmap.initSubArea(gardenId, () => {
    kmap.initTree(gardenId, () => {
      initSettingVal();
    });
  });
});

function selectDay(e) {
  kmap.refreshTree(gardenId, e, () => {
    initSettingVal();
  });
}

/**
 * @description:初始化赋值
 * @param {*}
 * @return {*}
 */
function initSettingVal() {
  if (recordId) {
    VE_API.nsjy.getNsRecord({ id: recordId }).then(({ data }) => {
      nsTypeIds.value = data.nsTypeIds ? data.nsTypeIds : [];
      drugList.value = data.drugList && data.drugList.length > 0 ? data.drugList : [{}];
      selectDateObj.value = {};
      treeIds.value = data.treeIds;
      subAreaIds.value = data.subAreaIds;
      desc.value = data.desc;
      execStyle.value = data.execStyle;
      execRange.value = data.execRange;
      reviewAfterDay.value = data.reviewAfterDay;

      initDrugList();
      loadSelectSubArea();
      loadSelectTree();
    });
  }
}

function changeNsType() {
  initDrugList();
}
function initNsTypeList() {
  VE_API.ns_type.list().then(({ data }) => {
    nsTypeList.value = data;
  });
}
function initDrugList() {
  VE_API.ns_drug.list({ nsTypeIds: nsTypeIds.value }).then(({ data }) => {
    nsDrugList.value = data;
  });
}

function addNsDrugItem() {
  drugList.value.push({ drugId: "" });
}
function deleteItem(i) {
  drugList.value.splice(i, 1);
}

//加载areaIds 数据选中
function loadSelectSubArea() {
  kmap.subAreaLayer.toggleSelect.getFeatures().clear();
  kmap.subAreaLayer.source.forEachFeature((f) => {
    let res = subAreaIds.value.find((id) => f.get("id") == id);
    if (res) {
      kmap.subAreaLayer.toggleSelect.getFeatures().push(f);
    }
  });
}

//加载treeIds 数据选中
function loadSelectTree() {
  kmap.treeLayer.toggleSelect.getFeatures().clear();
  let i = 0;
  kmap.treeFeatures.forEach((f) => {
    while (i < treeIds.value.length) {
      if (f.get("id") === treeIds.value[i]) {
        kmap.treeLayer.toggleSelect.getFeatures().push(f);
        i++;
      }
      break;
    }
  });
}

//设置treeIds subAreaIds
function setSubAreaIdsTreeIds() {
  let treeSelectedFeatures = kmap.treeLayer.toggleSelect.getFeatures();
  let subAreaSelectedFeatures = kmap.subAreaLayer.toggleSelect.getFeatures();
  treeIds.value = [];
  subAreaIds.value = [];
  subAreaSelectedFeatures.forEach((f) => {
    subAreaIds.value.push(f.get("id"));
  });
  treeSelectedFeatures.forEach((f) => {
    treeIds.value.push(f.get("id"));
    if (
      subAreaIds.value.findIndex(
        (subAreaId) => f.get("subAreaId") == subAreaId
      ) < 0
    ) {
      subAreaIds.value.push(f.get("subAreaId"));
    }
  });

  if (treeIds.value.length == 0) {
    ElMessage({
      message: "请选择树！",
      type: "warning",
    });
    return true;
  }
  return false;
}

/**
 * @description:提交
 * @param {*}
 * @return {*}
 */
const onSubmit = () => {
  //设置treeIds areaIds
  if (setSubAreaIdsTreeIds()) {
    return false;
  }
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (recordId) {
        form.id = recordId;
      }
      let res = await VE_API.nsjy.save(form);
      if (res.code == 0) {
        emit("back");
      }
    } else {
      console.log("error submit!!");
      return false;
    }
  });
};

const remove = () => {
  ElMessageBox.confirm("是否要删除这个农事?", "警告", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      VE_API.nsjy.remove({ id: recordId });
      ElMessage({
        type: "success",
        message: "删除成功！",
      });
      setTimeout(() => {
        emit("back");
      }, 500);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消",
      });
    });
};
</script>

<style lang="scss" scoped>
@import "../../styles/index.scss";
@import "./table.scss";
.container2 {
  height: 100%;
  width: 100%;
  z-index: 2;
  position: absolute;
}
.mainDiv {
  position: absolute;
  top: 100px;
  bottom: 50px;
  left: 20px;
  right: 20px;
  .leftBox {
    float: left;
    width: 500px;
    height: calc(100%);
    border: 1px solid rgba(81, 233, 240, 0.6);
    box-sizing: border-box;
    overflow-y: hidden;
    .myForm {
      box-sizing: border-box;
      overflow-y: auto;
      color: #fff;
      padding: 16px;
      height: calc(100% - 128px);
      .basis {
        margin-bottom: 22px;
        .basis-title {
          font-weight: normal;
          font-size: 17px;
          margin-bottom: 5px;
        }
        .basis-desc {
          font-weight: normal;
          font-size: 13px;
          color: #fe4646;
          padding: 12px;
          border-radius: 4px;
          border: 1px solid rgba(81, 233, 240, 0.59);
        }
      }
      .form {
        ::v-deep {
          .el-form-item__label {
            color: #fff;
          }
          .form-item {
            .el-radio-button__inner{
              background: #c3c5c6;
              border-radius: 5px;
              margin-right: 8px;
            }
            .el-select__wrapper {
              background: #032c39;
              border-radius: 4px;
              border: 1px solid rgba(81, 233, 240, 0.59);
              box-shadow: none;
              color: #fff;
            }
            .el-select__placeholder.is-transparent{
              color: rgba(0, 255, 240, 0.27);
            }
            .el-select__placeholder{
              color: #00FFF0;
            }
            .el-textarea {
              --el-input-placeholder-color: rgba(0, 255, 240, 0.27);
            }
            .el-textarea__inner {
              background: #032c39;
              border-radius: 4px;
              border: 1px solid rgba(81, 233, 240, 0.59);
              box-shadow: none;
              color: #fff;
            }
          }
        }
      }
    }
    .my-bottoms {
      border-top: 1px solid rgba(81, 233, 240, 0.6);
      box-sizing: border-box;
      text-align: center;
      padding: 20px 30px;
      .btn {
        color: #fff;
        width: 87px;
        height: 38px;
      }
      .btn-size {
        width: 141px;
      }
    }
  }
  .rightBox {
    float: right;
    width: calc(100% - 500px - 12px);
    height: 100%;
    background: #032c3940;
    border-radius: 4px;
    border: 1px solid rgba(81, 233, 240, 0.6);
    box-sizing: border-box;
    .head {
      // @include wh(calc(100% - 19px - 224px), 30px);
      display: flex;
      align-items: center;
      justify-content: space-around;
      margin-left: 19px;
      margin-right: 224px;
      .name {
        // @include wh(auto, 21px);
        font-weight: normal;
        font-size: 21px;
        line-height: 30px;
        color: #ffffff;
      }
      .line {
        width: calc(100% - 250px);
        border-bottom: 1px solid #51e9f0;
        opacity: 0.4;
        box-sizing: border-box;
        margin-top: 7px;
      }
      .rhombus {
        margin-top: 7px;
        // @include wh(50px, 15px);
        @include ossBg("rhombus.png");
      }
    }
    .map {
      margin: 19px 0px 0px 19px;
      // @include wh(calc(100% - 19px - 19px), calc(100% - 30px - 19px - 19px));
      position: relative;
      .tuli {
        position: absolute;
        right: 50px;
        bottom: 30px;
        z-index: 1000;
      }
      .tsyj {
        position: absolute;
        left: 100px;
        bottom: 0px;
        z-index: 1000;
      }
    }
  }
}
.calendar-item {
  // @include wh(100%, 100%);
  text-align: center;
}
.is-selected {
  color: #1989fa;
  background-color: yellow;
}
</style>
