<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="项目类型" prop="projectType">
        <el-select v-model="queryParams.projectType" placeholder="请选择项目类型" clearable>
          <el-option v-for="dict in pro_project_type" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['manage:proProjectInfo:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['manage:proProjectInfo:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['manage:proProjectInfo:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['manage:proProjectInfo:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="proProjectInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目名称" align="center" prop="projectName" width="250" />
      <el-table-column label="项目部门" align="center" prop="deptName" width="200" />
      <el-table-column label="项目简称" align="center" prop="simpleName" />
      <el-table-column label="项目类型" align="center" prop="projectType" width="100">
        <template #default="scope">
          <dict-tag :options="pro_project_type" :value="scope.row.projectType" />
        </template>
      </el-table-column>
      <el-table-column label="二维码" align="center" prop="projectQrCode" width="80">
        <template #default="scope">
          <image-preview :src="scope.row.projectQrCode" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="项目排序" align="center" prop="projectSort" width="120">
        <template #default="scope">
          <el-input-number size="mini" v-model="scope.row.projectSort" :min="1" :max="999"
            @change="setProjectSort(scope.row, $event)"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="项目地址" align="center" prop="projectAddress" width="250" />
      <el-table-column label="负责人" align="center" prop="projectPerson" width="100" />
      <el-table-column label="负责人电话" align="center" prop="projectPersonPhone" width="120" />
      <el-table-column label="项目工期" align="center" prop="projectTimeLimit" width="120">
        <template #default="scope">
          <el-tag effect="plain">
            {{ scope.row.projectTimeLimit + ' 天' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="总投资" align="center" prop="totalInvestment">
        <template #default="scope">
          <el-tag effect="dark">
            {{ scope.row.totalInvestment + ' 万元' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="合同金额" align="center" prop="contractAmount">
        <template #default="scope">
          <el-tag effect="dark">
            {{ scope.row.contractAmount + ' 万元' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="项目进度" align="center" prop="projectSchedule">
        <template #default="scope">
          <dict-tag :options="pro_project_schedule" :value="scope.row.projectSchedule" />
        </template>
      </el-table-column>
      <el-table-column label="计划开始时间" align="center" prop="scheduledStartTime" width="120" />
      <el-table-column label="计划完工时间" align="center" prop="plannedCompletionTime" width="120" />
      <el-table-column label="实际开始时间" align="center" prop="actualOperatingTime" width="120" />
      <el-table-column label="实际完工时间" align="center" prop="actualCompletionTime" width="120" />
      <el-table-column label="项目状态" align="center" prop="isDel">
        <template #default="scope">
          <dict-tag :options="sys_is_del" :value="scope.row.isDel" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:proProjectInfo:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:proProjectInfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改项目信息对话框 -->
    <el-dialog :title="title" v-model="open" width="1080px" append-to-body>
      <el-form ref="proProjectInfoRef" :model="form" :rules="rules" label-width="100px">
        <el-tabs v-model="activeName" type="card" class="demo-tabs">
          <el-tab-pane label="项目基本信息" name="base">
            <el-row :gutter="20">
              <el-col :span="16">
                <el-form-item label="归属单位" prop="deptId">
                  <el-select v-model="form.deptId" placeholder="请选择公司" clearable>
                    <el-option v-for="dict in deptOptions" :key="dict.deptId" :label="dict.deptName"
                      :value="dict.deptId"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="显示层级" prop="disDeptId">
                  <el-tree-select v-model="form.disDeptId" :data="deptOptions"
                    :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择显示层级"
                    check-strictly style="width:100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="16">
                <el-form-item label="项目名称" prop="projectName">
                  <el-input v-model="form.projectName" maxlength="64" show-word-limit placeholder="请输入项目名称" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="项目简称" prop="simpleName">
                  <el-input v-model="form.simpleName" maxlength="32" show-word-limit placeholder="请输入项目简称" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="项目类型" prop="projectType">
                  <el-select v-model="form.projectType" placeholder="请选择项目类型" style="width:100%">
                    <el-option v-for="dict in pro_project_type" :key="dict.value" :label="dict.label"
                      :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="项目负责人" prop="projectPerson">
                  <el-input v-model="form.projectPerson" maxlength="10" show-word-limit placeholder="请输入项目负责人" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="负责人电话" prop="projectPersonPhone">
                  <el-input v-model="form.projectPersonPhone" maxlength="11" show-word-limit placeholder="请输入负责人电话" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="项目地址" prop="projectAddress">
                  <el-input v-model="addressInfos" placeholder="请选择项目地址信息" @focus="getMapInfo">
                    <template #prefix>
                      <el-icon class="el-input__icon">
                        <Location />
                      </el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="项目工期" prop="projectTimeLimit">
                  <el-input v-model.number="form.projectTimeLimit" maxlength="10" show-word-limit placeholder="请输入项目工期">
                    <template #append>天</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="项目总投资" prop="totalInvestment">
                  <el-input v-model.number="form.totalInvestment" maxlength="20" show-word-limit placeholder="请输入项目总投资">
                    <template #append>万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同总金额" prop="contractAmount">
                  <el-input v-model.number="form.contractAmount" maxlength="20" show-word-limit placeholder="请输入合同总金额">
                    <template #append>万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="建筑面积" prop="floorArea">
                  <el-input v-model.number="form.floorArea" maxlength="20" show-word-limit placeholder="请输入项目建筑面积">
                    <template #append>㎡</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="项目进度" prop="projectSchedule">
                  <el-select v-model="form.projectSchedule" placeholder="请选择项目进度" style="width:100%">
                    <el-option v-for="dict in pro_project_schedule" :key="dict.value" :label="dict.label"
                      :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="计划开工时间" prop="scheduledStartTime">
                  <el-date-picker v-model="form.scheduledStartTime" type="date" placeholder="请选择计划开工时间"
                    style="width:100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="计划完工时间" prop="plannedCompletionTime">
                  <el-date-picker v-model="form.plannedCompletionTime" type="date" placeholder="请选择计划完工时间"
                    style="width:100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="实际开工时间" prop="actualOperatingTime">
                  <el-date-picker v-model="form.actualOperatingTime" type="date" placeholder="请选择实际开工时间"
                    style="width:100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="实际完工时间" prop="actualCompletionTime">
                  <el-date-picker v-model="form.actualCompletionTime" type="date" placeholder="请选择实际完工时间"
                    style="width:100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="项目概述" prop="projectSummarize">
                  <el-input v-model="form.projectSummarize" type="textarea" :rows="3" placeholder="请输入项目概述"
                    maxlength="1024" show-word-limit />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="参建单位信息" name="depts">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" icon="Plus" @click="handleAddDepts">添加</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" icon="Delete" @click="handleDeleteDepts">删除</el-button>
              </el-col>
            </el-row>
            <el-table :data="projectDeptsList" :row-class-name="rowProjectDeptsIndex"
              @selection-change="handleDeptsSelectionChange" ref="projectDeptsRef">
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column label="序号" align="center" prop="index" width="50" />
              <el-table-column label="单位类型" prop="deptType" align="center">
                <template #default="scope">
                  <el-select v-model="scope.row.deptType" placeholder="请选择单位类型">
                    <el-option v-for="dict in pro_dept_type" :key="dict.value" :label="dict.label"
                      :value="dict.value"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="单位负责人" prop="leader" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.leader" placeholder="请输入负责人姓名" />
                </template>
              </el-table-column>
              <el-table-column label="负责人联系电话" prop="phone" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.phone" placeholder="请输入负责人联系电话" />
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="项目大屏设置" name="setting">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="项目显示名" prop="orgName">
                  <el-input v-model="form.setting.orgName" maxlength="32" show-word-limit placeholder="请输入项目显示名" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="显示LOGO" prop="orgLogo">
                  <image-upload v-model="form.setting.orgLogo" :limit="1" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目平面图" prop="orgPlane">
                  <image-upload v-model="form.setting.orgPlane" :limit="3" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="项目图片" prop="orgImage">
                  <image-upload v-model="form.setting.orgImage" :limit="9" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="项目视频" prop="orgVideo">
                  <file-upload v-model="form.setting.orgVideo" :limit="1" :fileType="['mp4']" :fileSize="100" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <baidu-map ref="mapRef" @docom="mapDocom"></baidu-map>
  </div>
</template>

<script setup name="ProProjectInfo">
import { deptTreeSelect } from "@/api/system/user";
import { projectDeptList, deptTree, listDept } from "@/api/system/dept";
import { listProProjectInfo, getProProjectInfo, delProProjectInfo, addProProjectInfo, updateProProjectInfo } from "@/api/manage/proProjectInfo";
import BaiduMap from "@/components/BaiduMap/Map.vue";
import useUserStore from '@/store/modules/user'
const { proxy } = getCurrentInstance();
const { pro_project_type, pro_project_schedule, pro_dept_type, sys_is_del } = proxy.useDict('pro_project_type', 'pro_project_schedule', 'pro_dept_type', 'sys_is_del');

const mapRef = ref("");
const proProjectInfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const activeName = ref('base')
const addressInfos = ref("");
const projectDeptsList = ref([]);
const checkedProjectDepts = ref([]);

const deptOptions = ref([]);
const userStore = useUserStore()
const data = reactive({
  form: {
    setting: {}
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: null,
    visDeptId: null,
    disDeptId: null,
    projectName: null,
    projectCode: null,
    simpleName: null,
    projectType: null,
    projectLevel: null,
    projectPerson: null,
    projectPersonPhone: null,
    projectStatus: null,
    isDel: null,
  },
  rules: {
    deptId: [{ required: true, message: "所属部门不能为空", trigger: "change" }],
    disDeptId: [{ required: true, message: "显示层级不能为空", trigger: "change" }],
    projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
    simpleName: [{ required: false, message: "项目简称不能为空", trigger: "blur" }],
    projectType: [{ required: true, message: "项目类型不能为空", trigger: "change" }],
    projectPerson: [{ required: true, message: "项目负责人不能为空", trigger: "blur" }],
    projectPersonPhone: [{ required: true, message: "负责人电话不能为空", trigger: "blur" }],
    projectAddress: [{ required: false, message: "项目地址不能为空", trigger: "blur" }],
    projectTimeLimit: [{ required: true, message: "工程期限不能为空", trigger: "blur" }],
    totalInvestment: [{ required: true, message: "项目总投资不能为空", trigger: "blur" }],
    contractAmount: [{ required: true, message: "合同金额不能为空", trigger: "blur" }],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 地图选择 */
function mapDocom(pt, city) {
  form.value.projectAddress = (city.address || "") + (city.poi_desc || "");
  form.value.longitude = pt.lng.toFixed(5);
  form.value.latitude = pt.lat.toFixed(5);
  addressInfos.value = form.value.projectAddress + "," + form.value.longitude + "," + form.value.latitude;
}

/** 查询项目信息列表 */
function getList() {
  loading.value = true;
  listProProjectInfo(queryParams.value).then(response => {
    proProjectInfoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: null,
    visDeptId: null,
    disDeptId: null,
    projectName: null,
    projectCode: null,
    simpleName: null,
    projectType: null,
    projectLevel: null,
    projectRegional: null,
    projectAddress: null,
    projectNature: null,
    licenceNumber: null,
    projectPerson: null,
    projectPersonPhone: null,
    longitude: null,
    latitude: null,
    projectTimeLimit: null,
    totalInvestment: null,
    floorArea: null,
    totalOutputValue: null,
    plannedCompletionTime: null,
    scheduledStartTime: null,
    actualOperatingTime: null,
    actualCompletionTime: null,
    contractAmount: null,
    paidAmount: null,
    onAccountAmount: null,
    projectSchedule: null,
    projectSummarize: null,
    projectQrCode: null,
    projectStatus: null,
    projectSort: null,
    isDel: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    setting: {}
  };
  proxy.resetForm("proProjectInfoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加项目信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getProProjectInfo(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改项目信息";
  });
}

/** 参建单位序号 */
function rowProjectDeptsIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 参建单位添加按钮操作 */
function handleAddDepts() {
  let obj = {};
  obj.deptType = "";
  obj.deptName = "";
  obj.leader = "";
  obj.phone = "";
  projectDeptsList.value.push(obj);
}

/** 参建单位删除按钮操作 */
function handleDeleteDepts() {
  if (checkedProjectDepts.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的参建单位！");
  } else {
    const projectDeptsList = projectDeptsList.value;
    const checkedProjectDepts = checkedProjectDepts.value;
    projectDeptsList.value = projectDeptsList.filter(function (item) {
      return checkedProjectDepts.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleDeptsSelectionChange(selection) {
  checkedProjectDepts.value = selection.map(item => item.index)
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["proProjectInfoRef"].validate(valid => {
    if (valid) {
      form.value.projectDeptsList = projectDeptsList.value;
      if (form.value.id != null) {
        updateProProjectInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProProjectInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

//修改项目排序
function setProjectSort(row, val) {
  let param = {
    id: row.id,
    projectSort: val,
  };
  updateProProjectInfo(param).then((response) => {
    proxy.$modal.msgSuccess("修改成功");
    getList();
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除项目信息编号为"' + _ids + '"的数据项？').then(function () {
    return delProProjectInfo(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/proProjectInfo/export', {
    ...queryParams.value
  }, `proProjectInfo_${new Date().getTime()}.xlsx`)
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  listDept({ deptType: 2 }).then(response => {
    deptOptions.value = response.data;
  });
};

/** 地图选择 */
function getMapInfo() {
  mapRef.value.showDlg();
}


getList();
getDeptTree();
</script>
