<template>
  <scroll-view class="scroll-height" :scroll-y="true" :data-theme="'theme-' + proxy.$settingStore.themeColor.name">
    <view id="facilitiesGather">
      <view class="centerOne">
        <!-- <view class="title"> </view> -->

        <u--form :model="form" ref="uForm" :rules="rules" labelWidth="90">
          <view>
            <view style="padding: 10px 10px 20px 10px; background: #ffffff">
              <view style="padding-left: 9px">
                <u-form-item label="所属部门" prop="department" :borderBottom="true" @click="handleAction('所属部门')" required>
                  <u-input v-model="form.department" placeholder="请选择所属部门" suffixIcon="arrow-right" suffixIconStyle="color: #909399" border="none" disabledColor="transparent" disabled />
                </u-form-item>
                <u-form-item label="设施类型" prop="facilityTypeName" :borderBottom="true" @click="handleAction('设施类型')" required>
                  <u-input v-model="form.facilityTypeName" placeholder="请选择设施类型" suffixIcon="arrow-right" suffixIconStyle="color: #909399" border="none" disabledColor="transparent" disabled />
                </u-form-item>
                <u-form-item label="设施名称" prop="facilityName" :borderBottom="true" required>
                  <u-input v-model="form.facilityName" placeholder="请输入设施名称" border="none" />
                </u-form-item>
                <u-form-item label="状态" prop="status" :borderBottom="true" required>
                  <u-radio-group v-model="form.status" placement="row">
                    <u-radio v-for="se in sexList" :key="se" :activeColor="proxy.$settingStore.themeColor.color" :label="se.text" :name="se.value" style="margin-right: 15px"></u-radio>
                  </u-radio-group>
                </u-form-item>
                <u-form-item label="设施地址" prop="address" :borderBottom="true" required>
                  <u-input v-model="form.address" placeholder="请选择设施地址" border="none" disabledColor="transparent" disabled @click="handleAction('设施地址')">
                    <template #suffix>
                      <view class="iconfont ucicon-map menu-icon" style="font-size: 18px; color: #909399"> </view>
                    </template>
                  </u-input>
                </u-form-item>
                <u-form-item label="行政区划" prop="facilityAddress" :borderBottom="true" required>
                  <view style="width: 100%">
                    <view style="font-size: 15px"> {{ form.address ? form.address.split(form.facilityAddress)[0] : "" }}</view>
                    <u-input v-model="form.facilityAddress" placeholder="请输入详细地址" border="none" />
                  </view>
                </u-form-item>
                <u-form-item v-if="form.typeGuise && form.typeGuise != 1" label="类型" prop="gpsAreas" :borderBottom="true" @click="handleAction('类型')" required>
                  <view style="font-size: 15px">{{ form.typeGuise == 1 ? "点" : form.typeGuise == 2 ? "线" : form.typeGuise == 3 ? "面" : "" }}</view>
                  <view v-if="form.gpsAreas.length <= 0" style="font-size: 15px; margin: auto; color: #ff0000">未编辑</view>
                  <view v-if="form.gpsAreas.length > 0" style="font-size: 15px; margin: auto; color: #30bb00">已编辑</view>
                  <view class="iconfont ucicon-bianji1 menu-icon" style="font-size: 14px; color: #909399"> </view>
                </u-form-item>
                <u-form-item label="联系人" prop="contact" :borderBottom="true">
                  <u-input v-model="form.contact" placeholder="请输入联系人" border="none" />
                </u-form-item>
                <u-form-item label="联系电话" prop="contactPhone" :borderBottom="true">
                  <u-input v-model="form.contactPhone" placeholder="请输入联系电话" border="none" maxlength="11" />
                </u-form-item>
                <u-form-item label="设备图片" prop="imagesUrl" :borderBottom="true">
                  <oa-upload :uploadCount="1" :uploadImage="form.imagesUrl" @uploadSuccessChange="uploadSuccessChange" @uploadDeleteChange="uploadDeleteChange"></oa-upload>
                </u-form-item>
                <u-form-item label="备注" prop="facilityDesc" :borderBottom="true">
                  <u-textarea v-model="form.facilityDesc" placeholder="请输入" border="none" maxlength="30" style="padding: 0px"></u-textarea>
                </u-form-item>

                <u-form-item v-for="(fo, index) in form.extendData" :key="index" :label="fo.name" :prop="fo.key" :borderBottom="true">
                  <u-input v-if="fo.type === 'SRK'" v-model="fo.value" :placeholder="'请输入' + fo.name" border="none" disabledColor="transparent" />

                  <u-radio-group v-if="fo.type === 'DXK'" v-model="fo.value" placement="row">
                    <u-radio
                      v-for="se in fo.list"
                      :key="se"
                      :activeColor="proxy.$settingStore.themeColor.color"
                      :label="se.attributeValue"
                      :name="se.attributeCode"
                      style="margin-right: 15px"
                    ></u-radio>
                  </u-radio-group>

                  <u-input
                    v-if="fo.type === 'XLK'"
                    v-model="fo.valueName"
                    :placeholder="'请选择' + fo.name"
                    suffixIcon="arrow-right"
                    suffixIconStyle="color: #909399"
                    border="none"
                    disabledColor="transparent"
                    disabled
                    @click="handleAction('属性', fo)"
                  />
                </u-form-item>
              </view>
            </view>
          </view>
        </u--form>

        <view class="app-padding-bottom"> </view>

        <view class="app-button-fixed">
          <view class="app-flex">
            <u-button class="app-buttom" style="margin-right: 15px" @click="handleSubmit('取消')" shape="circle"> 取消 </u-button>

            <u-button class="app-buttom" type="primary" @click="handleSubmit('提交')" shape="circle"> 提交 </u-button>
          </view>
        </view>
      </view>

      <u-picker
        :show="actionShow"
        :columns="actionsList"
        :title="'请选择' + actionTitle"
        keyName="name"
        visibleItemCount="6"
        :defaultIndex="[actionDefaultIndex]"
        :closeOnClickOverlay="true"
        @close="actionShow = false"
        @cancel="actionShow = false"
        @confirm="selectAction"
        @change="changeHandler"
      ></u-picker>
    </view>
  </scroll-view>
</template>

<script setup>
import { onLoad, onShow, onHide, onLaunch, onReady } from "@dcloudio/uni-app";
import { ref, onMounted, inject, shallowRef, reactive, toRefs, getCurrentInstance } from "vue";
import { publicStores, useStores } from "@/store/modules/index";

import { typeSelect, add, uploadAvatar, treeselect } from "@/api/business/fireIot/facilitiesGather/index";

const { proxy } = getCurrentInstance();

const publicStore = publicStores();

//设施类型下拉数据存储
const typeSelectList = ref([[]]);
//部门下拉数据存储
const treeselectList = ref([[]]);
const childrenList1 = ref([[]]);

const dataList = reactive({
  sexList: [
    {
      text: "正常",
      value: "0",
    },
    {
      text: "维修",
      value: "1",
    },
    {
      text: "关闭",
      value: "2",
    },
  ],

  form: publicStore.$state.facilitiesGatherArray,

  rules: {
    department: [
      {
        required: false,
        message: "请选择所属部门",
        trigger: ["blur", "change"],
      },
    ],
    facilityTypeName: [
      {
        required: true,
        message: "请选择设施类型",
        trigger: ["blur", "change"],
      },
    ],
    facilityName: [
      {
        required: true,
        message: "请输入设施名称",
        trigger: ["blur", "change"],
      },
    ],
    status: [
      {
        required: true,
        message: "请选择设施状态",
        trigger: ["blur", "change"],
      },
    ],
    address: [
      {
        required: false,
        message: "请选择设施地址",
        trigger: ["blur", "change"],
      },
    ],
    facilityAddress: [
      {
        required: true,
        message: "请输入详细地址",
        trigger: ["blur", "change"],
      },
    ],
    // contact: [
    //   {
    //     required: true,
    //     message: "请输入联系人",
    //     trigger: ["blur", "change"],
    //   },
    // ],
    // contactPhone: [
    //   {
    //     required: true,
    //     message: "请输入联系人电话",
    //     trigger: ["blur", "change"],
    //   },
    //   {
    //     type: "string",
    //     min: 11,
    //     required: true,
    //     message: "请输入正确11位联系人电话",
    //     pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
    //     trigger: ["blur", "change"],
    //   },
    // ],
    // imagesUrl: [
    //   {
    //     required: true,
    //     message: "请选择图片",
    //     trigger: ["blur", "change"],
    //   },
    // ],
    // facilityDesc: [
    //   {
    //     required: true,
    //     message: "请输入备注",
    //     trigger: ["blur", "change"],
    //   },
    // ],
  },

  actionIndex: 0,
  actionIndex1: 0,
  actionTitle: "",
  actionShow: false,
  actionDefaultIndex: 0,
  actionsList: [[]],
});

const { sexList, form, rules, actionIndex, actionIndex1, actionTitle, actionShow, actionDefaultIndex, actionsList } = toRefs(dataList);

const uForm = ref(null);

/**
 * @初始化
 */
function init() {
  typeSelect({ id: "" }).then((requset) => {
    if (requset.status === "SUCCESS") {
      requset.data.forEach((el) => {
        typeSelectList.value[0].push({ name: el.typeName, value: el.id, typeGuise: el.typeGuise, dataField: el.dataField ? JSON.parse(el.dataField) : [] });
      });
    }
  });

  treeselect({}).then((requset) => {
    if (requset.status === "SUCCESS") {
      requset.data.forEach((el) => {
        treeselectList.value[0].push({ name: el.label, value: el.id, children: el.children });
      });

      var data = [
        {
          id: 124,
          label: "公司",
          children: [
            {
              id: 125,
              label: "it",
              children: [
                {
                  id: 126,
                  label: "二组",
                },
              ],
            },
          ],
        },
        {
          id: 124,
          label: "公司",
          children: [
            {
              id: 125,
              label: "it1",
              children: [
                {
                  id: 126,
                  label: "1组",
                },
              ],
            },
          ],
        },
        {
          id: 124,
          label: "公司",
          children: [
            {
              id: 125,
              label: "it2",
              children: [
                {
                  id: 126,
                  label: "3组",
                },
              ],
            },
          ],
        },
      ];

      data.forEach((el) => {
        treeselectList.value[0].push({ name: el.label, value: el.id, children: el.children });
      });
    }
  });
}

/**
 * @清空数据
 */
function wipeData() {
  form.value.department = ""; //所属部门
  form.value.facilityType = ""; //设施类型
  form.value.facilityTypeName = ""; //设施类型名称
  form.value.facilityName = ""; //设施名称
  form.value.status = "0"; //设施状态
  form.value.address = ""; //设施地址
  form.value.longitude = ""; //经度
  form.value.latitude = ""; //纬度
  form.value.province = ""; //省
  form.value.city = ""; //市
  form.value.area = ""; //区（县）
  form.value.facilityAddress = ""; //详细地址
  form.value.streetTown = null; //所属街镇
  form.value.gpsAreas = []; //经纬度集合
  form.value.contact = ""; //联系人
  form.value.contactPhone = ""; //联系方式
  form.value.imagesUrl = ""; //图⽚地址URL
  form.value.facilityDesc = ""; //备注
  form.value.extendData = []; //扩展属性
  form.value.recordPictureList = [];
  form.value.typeGuise = ""; //点线面类型
  form.value.gpsAreas = [];
}

/**
 * @api提交
 */
function handleSubmit(type) {
  let param = {};

  if (type == "提交") {
    uForm.value
      .validate()
      .then((res) => {
        uni.$u.toast("校验通过");

        param = {
          facilityType: form.value.facilityType,
          facilityName: form.value.facilityName,
          status: form.value.status, //设施状态
          address: "徐乐路208号", //设施地址
          longitude: "121.3632126", //经度
          latitude: "30.98168041", //纬度
          province: "", //省
          city: "", //市
          area: "", //区（县）
          facilityAddress: form.value.facilityAddress, //详细地址
          gpsAreas: "", //经纬度集合
          contact: form.value.contact, //联系人
          contactPhone: form.value.contactPhone, //联系方式
          imagesUrl: form.value.imagesUrl, //图⽚地址URL
          facilityDesc: form.value.facilityDesc, //备注
        };

        form.value.extendData.forEach((el) => {
          param.extendData.push({ key: el.key, value: el.value });
        });

        add(param).then((requset) => {
          if (requset.status === "SUCCESS") {
            proxy.$tab.navigateTo(`/pages/common/success/index?showNow=${false}`);
          }
        });
      })
      .catch((errors) => {
        uni.$u.toast("校验失败");
      });
  } else {
    proxy.$tab.navigateBack();
    wipeData();
  }
}

/**
 * @action弹出框点击事件
 */
function handleAction(value, array) {
  actionsList.value = [[]];

  if (value == "所属部门") {
    actionTitle.value = "所属部门";
    actionsList.value = treeselectList.value;

    treeselectList.value[0].forEach((el, ind) => {
      if (el.name === form.value.department) {
        actionDefaultIndex.value = ind;
      }
    });
  }

  if (value == "设施类型") {
    actionTitle.value = "设施类型";
    actionsList.value = typeSelectList.value;

    typeSelectList.value[0].forEach((el, ind) => {
      if (el.name === form.value.facilityTypeName) {
        actionDefaultIndex.value = ind;
      }
    });
  }

  if (value == "设施地址") {
    publicStore.$state.facilitiesGatherType = "点";
    proxy.$tab.navigateTo("/pages/business/fireIot/facilitiesGather/mapGather");
    return;
  }

  if (value == "类型") {
    if (form.value.typeGuise === 2) {
      publicStore.$state.facilitiesGatherType = "线";
    } else if (form.value.typeGuise === 3) {
      publicStore.$state.facilitiesGatherType = "面";
    }
    proxy.$tab.navigateTo("/pages/business/fireIot/facilitiesGather/mapGather");

    return;
  }

  if (value == "属性") {
    actionTitle.value = array.name;
    actionsList.value = [array.list];

    array.list.forEach((el, ind) => {
      if (el.value === array.value) {
        actionDefaultIndex.value = ind;
      }
    });
  }

  actionShow.value = true;
}

/**
 * @action弹出框选择事件
 */
function selectAction(e) {
  console.log(e);

  if (actionTitle.value == "设施类型") {
    wipeData();

    form.value.facilityType = e.value[0].value;
    form.value.facilityTypeName = e.value[0].name;
    form.value.typeGuise = e.value[0].typeGuise;

    if (e.value[0].dataField) {
      form.value.extendData = e.value[0].dataField;

      form.value.extendData.forEach((el) => {
        el.valueName = "";
        if (el.type === "XLK") {
          if (el.list) {
            el.list.forEach((e) => {
              e.name = e.attributeValue;
              e.value = e.attributeCode;
            });
          }
        }
      });
    } else {
      form.value.extendData = [];
    }
  }

  if (actionTitle.value.indexOf("属性") != -1) {
    form.value.extendData.forEach((el) => {
      if (el.type === "XLK") {
        el.valueName = e.value[0].name;
        el.value = e.value[0].value;
      }
    });
  }

  // if (actionTitle.value == "灭火器") {
  //   form.value.baseBuildList[actionIndex.value].baseBuildExtinguishList[actionIndex1.value].extinguishType = e.value[0].name;
  //   form.value.baseBuildList[actionIndex.value].baseBuildExtinguishList[actionIndex1.value].extinguishTypeValue = e.value[0].value;
  // }

  actionShow.value = false;
}

/**
 * @action弹出框change事件
 */
function changeHandler(e) {
  const uPicker = ref(null);
  const {
    columnIndex,
    value,
    values, // values为当前变化列的数组内容
    index,
    // 微信小程序无法将picker实例传出来，只能通过ref操作
    picker = uPicker.value,
  } = e;
  // 当第一列值发生变化时，变化第二列(后一列)对应的选项

  if (actionTitle.value == "所属部门") {
    console.log(columnIndex, index);

    if (columnIndex === 0) {
      // picker为选择器this实例，变化第二列对应的选项
      picker.setColumnValues(1, columnData[index]);
    }
  }
}

/**
 * @图片上传成功回调
 */
function uploadSuccessChange(e) {
  form.value.imagesUrl = e.url;
}

/**
 * @图片删除回调
 */
function uploadDeleteChange(e) {
  form.value.imagesUrl = "";
}

onLoad((options) => {
  init();
});

onShow(() => {
  //调用系统主题颜色
  proxy.$settingStore.systemThemeColor([1]);
});
</script>

<style lang="scss">
#facilitiesGather {
  .centerOne,
  .centerTwo {
    .title {
      color: #333333;
      text-align: center;
    }
  }

  :deep(.u-picker__view__column__item) {
    font-size: 13px;
  }

  :deep(.uni-select) {
    padding-left: 0;
    border: 0;
    font-size: 15px;
  }

  :deep(.uni-select__input-placeholder) {
    font-size: 15px;
    color: rgb(192, 196, 204);
  }

  :deep(.uni-select--mask) {
    position: relative;
  }
}
</style>
