<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="80%"
    :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"
                  :item-style="{ width: '360px', height: '240px' }"
                  :limit="1"
                  @upload="onUpload"
                />
              </div>
              <a-form-item label="主管部门" name="competentDepartment">
                <a-input
                  allow-clear
                  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="projectRegion">
                <a-input
                  allow-clear
                  placeholder="请输入项目地址"
                  v-model:value="form.projectRegion"
                />
              </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"
                  :customer-type="`empty`"
                  @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">
                <a-input
                  allow-clear
                  placeholder="请输入汽吊规格"
                  v-model:value="form.truckCraneSpecs"
                />
              </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">
                <SelectUser
                  :placeholder="`请选择所属人员`"
                  v-model:value="form.director"
                  @done="chooseDirector"
                />
              </a-form-item>
              <a-form-item label="项目可见范围" name="title" />
            </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-form-item label="业务负责人" name="salesman">
                <SelectUser
                  :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">
          <a-row :gutter="16">
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            />
            <a-col
              v-bind="
                styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 16 }
              "
            />
            <a-col
              v-bind="styleResponsive ? { md: 6, sm: 24, xs: 24 } : { span: 8 }"
            />
          </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-col
              v-bind="
                styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 16 }
              "
            />
            <a-col
              v-bind="styleResponsive ? { md: 6, sm: 24, xs: 24 } : { span: 8 }"
            />
          </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-col
              v-bind="
                styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 16 }
              "
            />
            <a-col
              v-bind="styleResponsive ? { md: 6, sm: 24, xs: 24 } : { span: 8 }"
            />
          </a-row>
        </a-card>
      </a-form>
    </div>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch, computed } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject, toDateString } from 'ele-admin-pro';
  import { addProject, updateProject } from '@/api/tower/project';
  import type { Project } from '@/api/tower/project/model';
  import { useUserStore } from '@/store/modules/user';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { UploadOutlined } from '@/layout/menu-icons';
  import {
    addTowerEquipment,
    updateTowerEquipment
  } from '@/api/tower/equipment';
  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 DictSelect from '@/views/search/components/dict-select.vue';
  import { User } from '@/api/system/user/model';

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  // 是否开启响应式布局
  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 dayTime = toDateString(new Date());
  // 已上传数据
  const images = ref<ItemType[]>([]);
  // 类型 single|multiple
  // const type = ref<string>('single');
  // 日期范围选择
  const dateRange = ref<[string, string]>(['', '']);

  // 穿梭框数据
  const breakfast = ref<any[]>();
  const targetKeys1 = ref<any[]>([]);
  const selectedKeys1 = ref<any[]>();
  const lunch = ref<any[]>();
  const targetKeys2 = ref<any[]>([]);
  const selectedKeys2 = ref<any[]>();
  const dinner = ref<any[]>();
  const targetKeys3 = ref<any[]>([]);
  const selectedKeys3 = ref<any[]>();
  const selectedGoodsIds = ref<any[]>([]);

  const formRef = ref<FormInstance | null>(null);

  // 合并选中的项目
  const onChange1 = () => {
    selectedGoodsIds.value = [
      ...targetKeys1.value,
      ...targetKeys2.value,
      ...targetKeys3.value
    ];
  };
  const onChange2 = () => {
    selectedGoodsIds.value = [
      ...targetKeys1.value,
      ...targetKeys2.value,
      ...targetKeys3.value
    ];
  };
  const onChange3 = () => {
    selectedGoodsIds.value = [
      ...targetKeys1.value,
      ...targetKeys2.value,
      ...targetKeys3.value
    ];
  };

  // 用户信息
  const form = reactive<Project>({
    projectId: undefined,
    projectName: '',
    companyName: '',
    customerName: '',
    projectRegion: '',
    projectAddress: '',
    longitude: '',
    latitude: '',
    superviseNo: '',
    licenceNo: '',
    securityStatus: undefined,
    competentDepartment: '',
    dismantlingCompany: '',
    truckCraneSpecs: '',
    contract: '',
    director: '',
    projectDirector: '',
    projectStatus: '',
    salesman: '',
    status: 0,
    userId: 0,
    comments: '',
    sortNumber: 100
  });

  /* 更新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'
      }
    ],
    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 { resetFields, validate, validateInfos } = useForm(form, rules);

  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 save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form
        };
        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 reload = () => {
    loading.value = true;
  };

  reload();

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignObject(form, props.data);
          reload();
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    }
  );
</script>
<style lang="less"></style>

<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;
  }
</style>
