<!--
 * @Author: your name
 * @Date: 2022-01-08 10:36:43
 * @LastEditTime: 2022-01-19 16:29:18
 * @LastEditors: Please set LastEditors
 * @Description: 基础资料 - 栋舍管理
 * @FilePath: \goldenPig\src\views\basic-data\house-admin\HouseAdmin.vue
-->
<template>
  <div class="house-admin">
    <search-cpn
      v-bind="searchConfig"
      @handleSearch="handleSearchEvent"
      @clearEvent="handleClearEvent"
    >
      <template #farmId="scope">
        <el-select
          v-model="searchForm2.farmId"
          :placeholder="scope.item.placeholder"
          style="width: 100%"
          clearable
          v-if="userItem.type === 0"
        >
          <el-option
            v-for="option in farmList"
            :key="option.id"
            :value="option.id"
            :label="option.farmName"
          >
          </el-option>
        </el-select>
      </template>
    </search-cpn>

    <table-cpn
      v-bind="tableConfig"
      @handleAddOrEdit="handleAddOrEditEvent"
      :searchForm="searchForm"
    >
      <!-- 状态 -->
      <template #tempAnomaly="scope">
        {{ statuses[scope.row.tempAnomaly - 1] }}
      </template>

      <!-- 阶段 -->
      <template #stage="scope">
        {{ stageList[scope.row.stage - 1].label }}
      </template>
    </table-cpn>

    <modal-cpn
      ref="modal"
      v-bind="modalConfig"
      :otherParams="modalForm2"
      :title="title"
    >
      <!-- 上级 -->
      <template #parentId="scope">
        <el-cascader
          :options="pigpenList"
          :props="{ checkStrictly: true }"
          :value="pigpenSelected"
          :disabled="optionsDisabled"
          @change="submitParentId"
          :placeholder="scope.item.placeholder"
          style="width: 100%"
        >
        </el-cascader>
      </template>
    </modal-cpn>
  </div>
</template>
<script>
// 搜索
import SearchCpn from "@/components/search-cpn";
import { formItemProp } from "./config/search.config";

// 表格
import TableCpn from "@/components/table-cpn";
import { propList } from "./config/table.config";

// 新增 or 编辑
import ModalCpn from "@/components/modal-cpn";
import { modalItemProp } from "./config/modal.config";

import {
  basePigpenList,
  basePigpenAdd,
  basePigpenEdit,
  basePigpenDel,
  basePigpenOptions, // 栋舍表二级，用于模态框
} from "@/utils/apis/basic-data/houseAdmin.js";

// import { baseFarmAll } from "@/utils/apis/basic-data/archivesAdmin.js";

// Vuex
import { mapState } from "vuex";

export default {
  components: {
    SearchCpn,
    TableCpn,
    ModalCpn,
  },
  computed: {
    ...mapState(["farmList", "farmId", "stageList"]),
  },
  data() {
    return {
      userItem: null, // 用户身份
      // 搜索
      searchConfig: {},
      searchForm1: {
        pigpenName: undefined,
      },
      searchForm2: {
        farmId: undefined,
      },
      searchForm: {
        pigpenName: undefined,
        farmId: undefined,
      },
      // 表格
      tableConfig: {},
      tableDataList: [],
      statuses: ["正常", "异常"],
      // 新增 or 编辑
      modalConfig: {},
      title: "",
      modalForm1: {
        pigpenName: "",
        pigpenTemp: "",
        tempAnomaly: 1,
        stage: "",
      },
      pigpenList: [], // 根据牧场所确定的栋舍(二级)
      pigpenSelected: [],
      modalForm2: {
        farmId: "",
        parentId: "",
        type: "",
      },
      optionsDisabled: false, // 用于级联选择器的报错，没有实际意义
    };
  },
  created() {
    // 获取用户身份
    this.userItem = JSON.parse(localStorage.getItem("gold_UserItem"));
    if (this.userItem.type === 0 && this.farmList.length > 0) {
      this.searchForm2.farmId = this.farmList[0]?.id;
      this.searchForm.farmId = this.farmList[0]?.id;
      this.modalForm2.farmId = this.farmList[0]?.id;
    }
    this.searchConfig = {
      formItemProp,
      searchForm: { ...this.searchForm1 },
    };
    this.tableConfig = {
      propList,
      permission: "archivesAdmin",
      requests: {
        list: basePigpenList,
        del: basePigpenDel,
      },
      tableStyle: {
        height: 700,
        footer: false,
        treeProps: { children: "children" },
      },
    };
    this.modalConfig = {
      modalItemProp,
      modalForm: this.modalForm1,
      requests: {
        add: basePigpenAdd,
        edit: basePigpenEdit,
      },
    };
    this.modalConfig.modalItemProp[4].options = this.stageList;
  },
  watch: {
    farmId: {
      handler(newVal) {
        if (!newVal) {
          return;
        }
        if (this.userItem && this.userItem.type !== 0) {
          // 确定默认选中牧场
          this.searchForm2.farmId = newVal;
          this.searchForm.farmId = newVal;
          this.modalForm2.farmId = newVal;
        }
      },
      immediate: true,
    },
    farmList: {
      handler(newVal) {
        if (!newVal) {
          return;
        }
        if (this.userItem && this.userItem.type === 0) {
          // 确定默认选中牧场
          this.searchForm2.farmId = newVal[0]?.id;
          this.searchForm.farmId = newVal[0]?.id;
          this.modalForm2.farmId = newVal[0]?.id;
        }
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    // 查询按钮 - 获取参数
    handleSearchEvent(params) {
      this.searchForm = {
        ...params,
        ...this.searchForm2,
      };
    },
    // 清空数据
    handleClearEvent() {
      this.searchForm2.farmId = undefined;
      this.searchForm.farmId = undefined;
    },
    // 模态框的 上级
    submitParentId(val) {
      this.modalForm2.parentId = val[val.length - 1];
      this.modalForm2.type = val.length;
    },
    // 新增 or 编辑事件
    async handleAddOrEditEvent(row) {
      // 牧场
      this.modalForm2.farmId = this.searchForm2.farmId;
      /* 模态框标题 - 牧场名称 */
      if (this.userItem.type === 0) {
        const farm = this.farmList.find(
          (item) => item.id === this.modalForm2.farmId
        );
        this.title = farm.farmName;
      }
      /* 栋舍表二级 */
      const pigpenOptions = await basePigpenOptions({
        farmId: this.modalForm2.farmId,
      });
      if (pigpenOptions.code === 10000) {
        // 递归函数：使返回值符合级联选择器的 label value
        const recursive = (arr) => {
          return arr.map((item) => {
            if (item.children && item.children.length > 0) {
              item.children = recursive(item.children);
            }
            return {
              label: item.pigpenName,
              value: item.id,
              farmId: item.farmId,
              children: item.children,
            };
          });
        };
        this.pigpenList = [
          {
            label: "顶级",
            value: 0,
            children: recursive(pigpenOptions.data),
          },
        ];
      } else {
        this.$message.error(pigpenOptions.message, "无法选择上级");
        return;
      }
      this.$refs["modal"].init(row);
      if (row.id) {
        this.modalForm2.farmId = row.farmId;
        this.modalForm2.parentId = row.parentId;
        this.modalForm2.type = row.type;
        if (row.grandId) {
          this.pigpenSelected = [0, row.grandId, row.parentId];
        } else if (row.parentId) {
          this.pigpenSelected = [0, row.parentId];
        } else {
          this.pigpenSelected = [0];
        }
      } else {
        this.pigpenSelected = [];
        this.modalForm2.type = "";
      }
    },
  },
};
</script>
<style scoped></style>
