<template>
  <div class="AddBuildingBox">
    <PageHeader :title="userid ? '编辑报修' : '添加报修'"></PageHeader>
    <div class="AddBuildingBody">
      <div class="title">基本信息</div>
      <div class="addBuildingFormBody">
        <el-form class="formBody" label-position="right" ref="formRef" :model="form" :rules="rules" label-width="130px">
          <el-row>
            <el-col :span="11">
              <el-form-item label="关联房屋" prop="houseId">
                <el-cascader v-model="form.houseId" :options="treedata" @change="handleChangehouse" />
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="维修项目" prop="maintenanceItemId">
                <el-cascader
                  :props="{
                    label: 'projectName',
                    value: 'id'
                  }"
                  v-model="form.maintenanceItemId"
                  placeholder="请选择维修项目"
                  :options="maintenanceItemTreeData"
                  @change="handleChangemaintenanceItem"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="问题描述" prop="problem">
                <el-input type="textarea" :rows="5" v-model.trim="form.problem" placeholder="请输入问题描述" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="报修人" prop="residentId">
                <Holder :userid="form.residentId" @change="handleChangeResident"></Holder>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phone">
                <el-input v-model.number="form.phone" placeholder="请输入手机号码" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="预约日期" prop="orderDate">
                <el-date-picker v-model="form.orderDate" type="date" placeholder="年/月/日" value-format="YYYY-MM-DD" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="问题图片" prop="remark">
                <el-upload
                  v-model:file-list="fileList"
                  :action="uploadUrl"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                >
                  <el-icon><Plus /></el-icon>
                </el-upload>
                <el-dialog v-model="dialogVisible">
                  <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item style="margin-top: 30px">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="cancelForm">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import PageHeader from '@/components/Pageheader/index.vue';
import { addMonthCard, getMonthCard, updateMonthCard } from '@/api/system/MonthCard';
import { getVillageTree } from '@/api/system/house';
import { getCommunitylistAPI } from '@/api/system/community';
import { convertBuildingToTree, hasFormData } from '@/utils/house';
import Holder from '@/components/Holder/index.vue';
import { UploadProps, UploadUserFile } from 'element-plus';
import { addRepair, getRepair, updateRepair, uploadRepairImages } from '@/api/system/Repair';
import { getRepairProject, gettreelistRepairProject } from '@/api/system/RepairProject';

const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/repair/uploadImages';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { com_pay_method } = toRefs<any>(proxy?.useDict('com_pay_method'));

const router = useRouter();
const route = useRoute();

const formRef = ref();
const form = ref({
  id: null,
  houseId: null, // 关联房屋id
  maintenanceItemId: null, // 维修项目id
  problem: '', // 问题描述
  residentId: null, // 报修人id(住户表id)
  phone: null, // 报手机号码
  problemImageUrl: '', // 问题图片地址
  problemStatus: '0', // 0 已提交 1已分配 2维修中 3维修完成
  repairDes: '', // 维修描述
  repairImageUrl: '', // 维修图片url
  orderDate: '' // 预约日期
});
const rules = ref({
  houseId: [{ required: true, message: '请选择关联房屋', trigger: 'blur' }],
  maintenanceItemId: [{ required: true, message: '请选择维修项目', trigger: 'blur' }],
  problem: [{ required: true, message: '请输入问题描述', trigger: 'blur' }]
});
const userid = ref(null);
// 当前小区
const currentviliage = ref();
// 树形结构
const treedata = ref();
// 报修项目 tree 结构
const maintenanceItemTreeData = ref();
function init() {
  getCommunitylistAPI().then((res) => {
    currentviliage.value = res.rows.find((item) => item.choiceStatus === 0);
    getVillageTree(currentviliage.value.villageId).then((res) => {
      treedata.value = convertBuildingToTree(res.data.buildings);
    });

    gettreelistRepairProject().then((res) => {
      maintenanceItemTreeData.value = res.data;
      if (route.query.id) {
        userid.value = route.query.id;
        form.value.id = userid.value;
        getRepair(userid.value).then((res) => {
          form.value = {
            ...form.value,
            ...res.data
          };
          fileList.value = form.value.problemImageUrl
            .split(',')
            .map((item) => {
              if (!item) return undefined;
              return {
                name: item.split('/').pop(),
                url: item
              };
            })
            .filter((item) => item);
          console.log(fileList.value);
        });
      }
    });
  });
}
init();

// ! 上传图片 =--==================================================================
const fileList = ref<UploadUserFile[]>([]);

const dialogImageUrl = ref('');
const dialogVisible = ref(false);

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

// !== 选择报修人 ====================================================================
function handleChangeResident(val: string | number) {
  console.log(val);
  form.value.residentId = val;
}

// !== 房屋 ===========================================================================
function handleChangehouse(val: (string | number)[]) {
  if (val.length >= 3) {
    form.value.houseId = val.pop() as number;
  } else {
    form.value.houseId = null;
  }
}
function handleChangemaintenanceItem(val: (string | number)[]) {
  console.log(val);
  if (val.length >= 2) {
    form.value.maintenanceItemId = val.pop() as number;
  } else {
    form.value.maintenanceItemId = null;
  }
}

// !== 提交 =============================================================================
// 提交
const submitForm = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      let str = '';
      if (fileList.value.length > 0) {
        // 有图片
        const formdata = new FormData();
        fileList.value.forEach((item) => {
          if (item.raw && item.raw instanceof File) {
            formdata.append('files', item.raw);
          } else {
            str += item.url + ',';
          }
        });
        if (!hasFormData(formdata)) return sendForm(str);
        uploadRepairImages(formdata).then((res) => {
          const successlist = res.data.success;
          const errorlist = res.data.error;
          if (successlist.length > 0) {
            successlist.forEach((item) => {
              str += item.url + ',';
            });
          }
          if (errorlist.length > 0) {
            errorlist.forEach((item) => {
              fileList.value = fileList.value.filter((file) => file.name !== item);
            });
            ElMessage.error('图片上传失败： ' + errorlist.join(','));
          }
          sendForm(str);
        });
      } else {
        sendForm(str);
      }
    }
  });
};

const sendForm = (str: string) => {
  form.value.problemImageUrl = str;
  if (userid.value) {
    updateRepair(form.value).then((res) => {
      console.log(res);
      ElMessage.success('编辑成功');
      cancelForm();
    });
  } else {
    addRepair(form.value).then((res) => {
      console.log(res);
      ElMessage.success('添加成功');

      cancelForm();
    });
  }
};
// 推出
const cancelForm = () => {
  router.push({
    path: '/repair/repairlist'
  });
};
</script>

<style scoped lang="scss">
.AddBuildingBox {
  padding: 15px;
  height: 100%;
  width: 100%;
}
.AddBuildingBody {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background-color: white;
  padding: 15px;
  .title {
    height: 40px;
    line-height: 40px;
    padding-left: 20px;
    background-color: rgba(255, 255, 255, 1);
    color: rgba(16, 16, 16, 1);
    border-bottom: 1px solid #bbbbbb;
    margin-bottom: 60px;
  }

  .formBody {
    width: 1050px;
    margin: 0 auto;

    &:deep(.el-date-editor.el-input) {
      width: inherit;
    }

    &:deep(.el-form-item__content, .el-select, .el-input) {
      width: 385px !important;
      margin-right: 10px;
      .el-cascader {
        width: 100%;
      }
    }
    .el-form-item {
      margin-bottom: 20px;
      align-items: center;
    }
    .el-button {
      width: 80px;
      height: 35px;
      margin-right: 20px;
    }
  }
}
</style>
