<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="90%"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑项目' : '添加项目'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <div style="background-color: #f3f3f3; padding: 8px">
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ md: { span: 7 }, sm: { span: 4 }, xs: { span: 24 } }"
        :wrapper-col="{ md: { span: 17 }, sm: { span: 20 }, xs: { span: 24 } }"
      >
        <a-card title="项目信息" :bordered="false">
          <a-row :gutter="16">
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <div class="upload-image">
                <ele-image-upload
                  v-model:value="images"
                  :limit="6"
                  :drag="true"
                  :item-style="{ width: '120px', height: '90px' }"
                  :upload-handler="uploadHandler"
                  @upload="onUpload"
                />
              </div>
              <a-form-item label="主管部门" name="competentDepartment">
                <DictSelect
                  dict-code="Department"
                  placeholder="请选择主管部门"
                  v-model:value="form.competentDepartment"
                />
              </a-form-item>
              <a-form-item label="合同其他说明" name="contract">
                <a-input
                  allow-clear
                  placeholder="请输入合同其他说明"
                  v-model:value="form.contract"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="项目名称" name="projectName">
                <a-input
                  allow-clear
                  placeholder="请输入项目名称"
                  v-model:value="form.projectName"
                />
              </a-form-item>
              <a-form-item label="租赁单位" name="companyName">
                <TowerCompany
                  :placeholder="`请选择租赁单位`"
                  v-model:value="form.companyName"
                  :customer-type="`产权单位`"
                  @done="chooseCompanyName"
                />
              </a-form-item>
              <a-form-item label="项目地址" name="region">
                <a-input-group compact>
                  <a-input
                    disabled
                    style="width: calc(100% - 32px)"
                    v-model:value="form.projectRegion"
                    placeholder="所属区域"
                  />
                  <a-tooltip title="选择位置">
                    <a-button @click="openMapPicker">
                      <template #icon><EnvironmentOutlined /></template>
                    </a-button>
                  </a-tooltip>
                </a-input-group>
              </a-form-item>
              <a-form-item label="经度" name="longitude">
                <a-input
                  allow-clear
                  placeholder="请输入经度"
                  v-model:value="form.longitude"
                />
              </a-form-item>
              <a-form-item label="纬度" name="latitude">
                <a-input
                  allow-clear
                  placeholder="请输入纬度"
                  v-model:value="form.latitude"
                />
              </a-form-item>
              <a-form-item label="施工许可证" name="licenceNo">
                <a-input
                  allow-clear
                  placeholder="请输入施工许可证"
                  v-model:value="form.licenceNo"
                />
              </a-form-item>
              <a-form-item label="安拆单位" name="dismantlingCompany">
                <TowerCompany
                  :placeholder="`请选择安拆单位`"
                  v-model:value="form.dismantlingCompany"
                  :customer-type="`产权单位`"
                  @done="chooseDismantlingCompany"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="项目状态" name="projectStatus">
                <DictSelect
                  dict-code="ProjectStatus"
                  placeholder="请选择项目状态"
                  v-model:value="form.projectStatus"
                />
              </a-form-item>
              <a-form-item label="承租单位" name="customerName">
                <TowerCompany
                  :placeholder="`请选择承租单位`"
                  v-model:value="form.customerName"
                  @done="chooseCustomerName"
                />
              </a-form-item>
              <a-form-item label="详细地址" name="projectAddress">
                <a-input
                  allow-clear
                  placeholder="请输入详细地址"
                  v-model:value="form.projectAddress"
                />
              </a-form-item>
              <a-form-item label="报监编号" name="superviseNo">
                <a-input
                  allow-clear
                  placeholder="请输入报监编号"
                  v-model:value="form.superviseNo"
                />
              </a-form-item>
              <a-form-item label="安全状态" name="securityStatus">
                <DictSelect
                  dict-code="SecurityStatus"
                  v-model:value="form.securityStatus"
                  placeholder="选择安全状态"
                />
              </a-form-item>
              <a-form-item label="汽吊规格" name="truckCraneSpecs">
                <DictSelectMultiple
                  dict-code="TruckCraneSpecs"
                  v-model:value="form.truckCraneSpecs"
                  placeholder="选择汽吊规格"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>

        <a-divider style="height: 8px" />
        <a-card title="项目分配" :bordered="false">
          <a-row :gutter="16">
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="项目负责人" name="director">
                <SelectStaff
                  :placeholder="`请选择所属人员`"
                  v-model:value="form.director"
                  @done="chooseDirector"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="项目经理" name="projectDirector">
                <a-input
                  allow-clear
                  placeholder="请输入项目经理"
                  v-model:value="form.projectDirector"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="业务负责人" name="salesman">
                <SelectStaff
                  :placeholder="`请选择业务负责人`"
                  v-model:value="form.salesman"
                  @done="chooseSalesman"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>

        <a-divider style="height: 8px" />
        <a-card title="项目成员" :bordered="false">
          <UserList :project-id="form.projectId" v-model:value="form.users" />
        </a-card>

        <a-divider style="height: 8px" />
        <a-card title="合同签订设备清单" :bordered="false">
          <EquipmentList
            :project-id="form.projectId"
            v-model:value="form.orders"
          />
        </a-card>

        <a-divider style="height: 8px" />
        <a-card title="检查/保养部位配置" :bordered="false">
          <a-tabs v-model:activeKey="activeKey" type="card" @change="onChange">
            <a-tab-pane key="1" tab="检查部位">
              <InspectList
                :project-id="form.projectId"
                v-model:value="form.places1"
                @done="reload"
                @search="onSearch"
              />
            </a-tab-pane>
            <a-tab-pane key="2" tab="保养部位" force-render>
              <MaintenanceList
                :project-id="form.projectId"
                v-model:value="form.places2"
                @done="reload"
                @search="onSearch"
              />
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-form>
      <!-- 地图位置选择弹窗 -->
      <ele-map-picker
        :need-city="true"
        :dark-mode="darkMode"
        v-model:visible="showMap"
        :center="[108.374959, 22.767024]"
        :search-type="1"
        :zoom="12"
        @done="onDone"
      />
    </div>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import { addProject, updateProject } from '@/api/tower/project';
  import type { Project } from '@/api/tower/project/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { EnvironmentOutlined } from '@ant-design/icons-vue';
  import { FormInstance } from 'ant-design-vue/es/form';
  import { Customer } from '@/api/oa/customer/model';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { User } from '@/api/system/user/model';
  import { uploadFile } from '@/api/system/file';
  import { FILE_SERVER } from '@/config/setting';
  import UserList from './user-list.vue';
  import EquipmentList from './equipment-list.vue';
  import InspectList from './inspect-list.vue';
  import MaintenanceList from './maintenance-list.vue';
  import { CenterPoint } from 'ele-admin-pro/es/ele-map-picker/types';
  import { listProjectUser } from '@/api/tower/project/user';
  import { listProjectOrder } from '@/api/tower/project/order';
  import { listProjectPlace } from '@/api/tower/project/place';
  import useFormData from '@/utils/use-form-data';

  // 是否是修改
  const isUpdate = ref(false);
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Project | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  // 已上传数据
  const images = ref<ItemType[]>([]);
  // 是否显示地图选择弹窗
  const showMap = ref(false);
  const activeKey = ref<string>('1');
  const keywords = ref<string>();
  // 省市区
  const city = ref<string[]>([]);
  const { darkMode } = storeToRefs(themeStore);
  const formRef = ref<FormInstance | null>(null);

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<Project>({
    projectId: undefined,
    projectName: '',
    projectImage: '',
    files: undefined,
    companyName: '',
    customerName: '',
    projectRegion: '',
    projectAddress: '',
    longitude: '',
    latitude: '',
    superviseNo: '',
    licenceNo: '',
    securityStatus: undefined,
    competentDepartment: undefined,
    dismantlingCompany: '',
    truckCraneSpecs: undefined,
    contract: '',
    director: '',
    projectDirector: '',
    projectStatus: undefined,
    salesman: '',
    status: 0,
    userId: 0,
    comments: '',
    sortNumber: 100,
    users: [],
    orders: [],
    places1: [],
    places2: []
  });

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单验证规则
  const rules = reactive({
    projectName: [
      {
        required: true,
        type: 'string',
        message: '请输入项目名称',
        trigger: 'blur'
      }
    ],
    projectCode: [
      {
        required: true,
        type: 'string',
        message: '请输入合法的IP地址',
        trigger: 'blur'
      }
    ],
    projectStatus: [
      {
        required: true,
        type: 'string',
        message: '请选择项目状态',
        trigger: 'blur'
      }
    ],
    progress: [
      {
        required: true,
        type: 'string',
        message: '请选择跟进状态',
        trigger: 'blur'
      }
    ],
    securityStatus: [
      {
        required: true,
        type: 'string',
        message: '请选择安全状态',
        trigger: 'blur'
      }
    ],
    companyName: [
      {
        required: true,
        type: 'string',
        message: '请选择租赁单位',
        trigger: 'blur'
      }
    ],
    customerName: [
      {
        required: true,
        type: 'string',
        message: '请选择承租单位',
        trigger: 'blur'
      }
    ],
    projectRegion: [
      {
        required: true,
        type: 'string',
        message: '请输入项目地址',
        trigger: 'blur'
      }
    ]
  });

  const chooseCompanyName = (data: Customer) => {
    form.companyName = data.customerName;
  };

  const chooseCustomerName = (data: Customer) => {
    form.customerName = data.customerName;
  };

  const chooseDismantlingCompany = (data: Customer) => {
    form.dismantlingCompany = data.customerName;
  };

  const chooseDirector = (data: User) => {
    form.director = data.nickname;
  };

  const chooseSalesman = (data: User) => {
    form.salesman = data.nickname;
  };

  /* 地图选择后回调 */
  const onDone = (location: CenterPoint) => {
    console.log(location);
    city.value = [
      `${location.city?.province}`,
      `${location.city?.city}`,
      `${location.city?.district}`
    ];
    form.projectRegion = `${location.city?.city} ${location.city?.district}`;
    form.projectAddress = `${location.address}`;
    form.latitude = `${location.lat}`;
    form.longitude = `${location.lng}`;
    showMap.value = false;
  };

  /* 打开位置选择 */
  const openMapPicker = () => {
    showMap.value = true;
  };

  /* 上传事件 */
  const uploadHandler = (file: File) => {
    const item: ItemType = {
      file,
      uid: (file as any).uid,
      name: file.name
    };
    if (!file.type.startsWith('image')) {
      message.error('只能选择图片');
      return;
    }
    if (file.size / 1024 / 1024 > 2) {
      message.error('大小不能超过 2MB');
      return;
    }
    onUpload(item);
  };

  // 上传文件
  const onUpload = (item) => {
    const { file } = item;
    uploadFile(file)
      .then((data) => {
        images.value.push({
          uid: data.id,
          url: FILE_SERVER + data.path,
          status: 'done'
        });
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  const onSearch = (text) => {
    keywords.value = text;
    reload();
  };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form,
          projectImage: JSON.stringify(images.value),
          truckCraneSpecs: JSON.stringify(form.truckCraneSpecs)
        };
        const saveOrUpdate = isUpdate.value ? updateProject : addProject;
        saveOrUpdate(formData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  const onChange = () => {
    if (activeKey.value == '1') {
      keywords.value = '巡检';
    }
    if (activeKey.value == '2') {
      keywords.value = '保养';
    }
    if (isUpdate.value) {
      reload();
    }
  };

  const reload = () => {
    loading.value = true;
    if (props.data?.projectId) {
      // 加载项目成员
      listProjectUser({
        projectId: props.data?.projectId
      })
        .then((data) => {
          form.users = data;
        })
        .catch((e) => {
          message.error(e.message);
        });
      // 加载项目合同预定设备清单
      listProjectOrder({ projectId: props.data?.projectId })
        .then((data) => {
          form.orders = data.map((d) => {
            return {
              ...d,
              isEdit: false
            };
          });
        })
        .catch((e) => {
          message.error(e.message);
        });
      // 加载检查/保养部位配置
      listProjectPlace({
        projectId: props.data?.projectId,
        keywords: '巡检'
      })
        .then((data) => {
          form.places1 = data;
        })
        .catch((e) => {
          message.error(e.message);
        });
      // 加载检查/保养部位配置
      listProjectPlace({
        projectId: props.data?.projectId,
        keywords: '保养'
      })
        .then((data) => {
          form.places2 = data;
        })
        .catch((e) => {
          message.error(e.message);
        });
    }
  };
  reload();

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignFields({
            ...props.data
          });
          images.value = [];
          if (props.data.projectImage) {
            const arr = JSON.parse(props.data.projectImage);
            arr.map((d) => {
              images.value.push({
                uid: d.uid,
                url: d.url,
                status: 'done'
              });
            });
          }
          if (props.data.truckCraneSpecs) {
            form.truckCraneSpecs = JSON.parse(props.data.truckCraneSpecs);
          }
          reload();
          isUpdate.value = true;
        } else {
          images.value = [];
          form.places1 = [];
          form.places2 = [];
          form.users = [];
          form.orders = [];
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    }
  );
</script>
<style lang="less">
  .tab-pane {
    min-height: 300px;
  }

  .ml-10 {
    margin-left: 5px;
  }

  .upload-text {
    margin-right: 70px;
  }

  .upload-image {
    margin-bottom: 30px;
    display: flex;
    justify-content: center;
    text-align: center;
  }
</style>
