<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item>
          <template slot="label">{{ dmT("queryReportTime") }}</template>
          <el-date-picker
            v-model="queryDateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="-"
            :start-placeholder="dmT('queryDateRangePh')"
            :end-placeholder="dmT('queryDateRangeEndPh')"
            clearable
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item prop="townDeptId">
          <template slot="label">{{ dmT("queryTown") }}</template>
          <el-select v-model="queryParams.townDeptId" :placeholder="dmCommon('pleaseSelect')" clearable filterable style="width: 180px">
            <el-option v-for="item in townOptions" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
          </el-select>
        </el-form-item>
        <el-form-item prop="villageDeptId">
          <template slot="label">{{ dmT("queryVillage") }}</template>
          <el-select
            v-model="queryParams.villageDeptId"
            :placeholder="dmT('phVillageSearch')"
            clearable
            filterable
            style="width: 220px"
          >
            <el-option
              v-for="item in villageOptions"
              :key="'q-v-' + item.deptId"
              :label="item.label"
              :value="item.deptId"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item prop="problemType">
          <template slot="label">{{ dmT("queryProblemType") }}</template>
          <el-select v-model="queryParams.problemType" :placeholder="dmCommon('pleaseSelect')" clearable style="width: 140px">
            <el-option v-for="item in problemTypeOptions" :key="'q-t-' + item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ dmCommon("search") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ dmCommon("reset") }}</el-button>
          <el-button
            v-hasPermi="['dataModel:threeAssetsProblemReport:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ dmCommon("add") }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br />

    <el-card shadow="never">
      <el-table v-loading="loading" :data="tableList" border>
        <template slot="empty">
          <span>{{ dmT("emptyList") }}</span>
        </template>
        <el-table-column :label="dmT('colReportTime')" align="center" min-width="160">
          <template slot-scope="scope">{{ formatReportTime(scope.row.reportTime) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colTownName')" prop="townName" align="center" min-width="110" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colVillageName')" prop="villageName" align="center" min-width="110" :show-overflow-tooltip="true" />
        <!-- <el-table-column :label="dmT('colProblemType')" align="center" min-width="110">
          <template slot-scope="scope">{{ problemTypeLabel(scope.row.problemType) }}</template>
        </el-table-column> -->
        <el-table-column :label="dmT('colProblemLevel')" align="center" width="100">
          <template slot-scope="scope">{{ problemLevelLabel(scope.row.problemLevel) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colProblemDetail')" prop="problemDetail" align="center" min-width="180" :show-overflow-tooltip="true" />
        <el-table-column :label="dmCommon('colOp')" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button v-hasPermi="['dataModel:threeAssetsProblemReport:query']" type="text" size="mini" @click="handleView(scope.row)">{{ dmCommon("view") }}</el-button>
            <el-button v-hasPermi="['dataModel:threeAssetsProblemReport:edit']" type="text" size="mini" @click="handleEdit(scope.row)">{{ dmCommon("edit") }}</el-button>
            <el-button v-hasPermi="['dataModel:threeAssetsProblemReport:remove']" type="text" size="mini" @click="handleDelete(scope.row)">{{ dmCommon("delete") }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <el-dialog :title="dialogTitle" :visible.sync="open" width="720px" append-to-body @close="cancel">
      <el-form :key="formKey" ref="form" :model="form" class="tapr-form" label-width="140px" size="small">
        <div class="tapr-section-title">{{ dmT("sectionBasic") }}</div>
        <el-form-item prop="reportTime" :rules="formRules.reportTime">
          <template slot="label">{{ dmT("formReportTime") }}</template>
          <el-date-picker
            v-model="form.reportTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            :placeholder="dmCommon('pleaseSelect')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item prop="villageDeptId" :rules="formRules.villageDeptId">
          <template slot="label">{{ dmT("formVillage") }}</template>
          <el-select
            v-model="form.villageDeptId"
            :placeholder="dmT('phVillageSearch')"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in villageOptions"
              :key="'f-v-' + item.deptId"
              :label="item.label"
              :value="item.deptId"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item prop="problemType" :rules="formRules.problemType">
          <template slot="label">{{ dmT("formProblemType") }}</template>
          <el-select v-model="form.problemType" :placeholder="dmCommon('pleaseSelect')" style="width: 100%">
            <el-option v-for="item in problemTypeOptions" :key="'f-t-' + item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item> -->
        <el-form-item prop="problemLevel" :rules="formRules.problemLevel">
          <template slot="label">{{ dmT("formProblemLevel") }}</template>
          <el-radio-group v-model="form.problemLevel">
            <el-radio v-for="item in problemLevelOptions" :key="'f-l-' + item.value" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="problemDetail" :rules="formRules.problemDetail">
          <template slot="label">{{ dmT("formProblemDetail") }}</template>
          <el-input
            v-model="form.problemDetail"
            type="textarea"
            :rows="4"
            :placeholder="dmT('phProblemDetail')"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>
        <el-form-item prop="handleResult" :rules="formRules.handleResult">
          <template slot="label">{{ dmT("formHandleResult") }}</template>
          <el-input
            v-model="form.handleResult"
            type="textarea"
            :rows="3"
            :placeholder="dmT('phHandleResult')"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ dmCommon("ok") }}</el-button>
        <el-button @click="cancel">{{ dmCommon("cancel") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dmCommon('viewTitle')" :visible.sync="viewOpen" width="720px" append-to-body>
      <el-form class="dm-view-form tapr-form" label-width="140px" size="small">
        <div class="tapr-section-title">{{ dmT("sectionBasic") }}</div>
        <el-form-item :label="dmT('formReportTime')">
          <span>{{ formatReportTime(viewRow.reportTime) }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formTown')">
          <span>{{ viewRow.townName || dash }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formVillage')">
          <span>{{ viewRow.villageName || dash }}</span>
        </el-form-item>
        <!-- <el-form-item :label="dmT('formProblemType')">
          <span>{{ problemTypeLabel(viewRow.problemType) }}</span>
        </el-form-item> -->
        <el-form-item :label="dmT('formProblemLevel')">
          <span>{{ problemLevelLabel(viewRow.problemLevel) }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formProblemDetail')">
          <span class="tapr-view-text">{{ viewRow.problemDetail || dash }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formHandleResult')">
          <span class="tapr-view-text">{{ viewRow.handleResult || dash }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-hasPermi="['dataModel:threeAssetsProblemReport:edit']" type="primary" @click="handleEditFromView">{{ dmCommon("edit") }}</el-button>
        <el-button @click="viewOpen = false">{{ dmCommon("close") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dataModelLocaleMixin from "@/mixins/dataModelLocaleMixin"
import {
  listThreeAssetsProblemReport,
  getThreeAssetsProblemReport,
  addThreeAssetsProblemReport,
  updateThreeAssetsProblemReport,
  delThreeAssetsProblemReport,
  listThreeAssetsProblemReportTownOptions,
  listThreeAssetsProblemReportVillageTree
} from "@/api/dataModel/threeAssetsProblemReport"

const PROBLEM_TYPE_VALUES = ["fund", "asset", "resource", "other"]
const PROBLEM_LEVEL_VALUES = ["general", "key", "major"]

function createEmptyForm() {
  return {
    id: undefined,
    reportTime: undefined,
    villageDeptId: undefined,
    problemType: undefined,
    problemLevel: undefined,
    problemDetail: undefined,
    handleResult: undefined
  }
}

function normalizeForm(data) {
  return Object.assign(createEmptyForm(), data || {})
}

function flattenVillageOptions(tree) {
  const list = []
  ;(tree || []).forEach((county) => {
    ;(county.children || []).forEach((town) => {
      ;(town.children || []).forEach((village) => {
        if (village == null || village.id == null) {
          return
        }
        const townName = town.label || ""
        const villageName = village.label || ""
        list.push({
          deptId: village.id,
          label: townName ? `${townName} / ${villageName}` : villageName
        })
      })
    })
  })
  return list
}

export default {
  name: "ThreeAssetsProblemReport",
  mixins: [dataModelLocaleMixin],
  data() {
    return {
      dmNs: "threeAssetsProblemReport",
      loading: false,
      open: false,
      viewOpen: false,
      dialogEdit: false,
      formKey: 0,
      total: 0,
      tableList: [],
      townOptions: [],
      villageOptions: [],
      queryDateRange: null,
      viewRow: {},
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        townDeptId: undefined,
        villageDeptId: undefined,
        problemType: undefined,
        beginReportTime: undefined,
        endReportTime: undefined
      },
      form: createEmptyForm()
    }
  },
  computed: {
    dash() {
      return this.$t("dataModel.status.dash")
    },
    dialogTitle() {
      return this.dialogEdit ? this.dmT("dialogEdit") : this.dmT("dialogAdd")
    },
    problemTypeOptions() {
      return PROBLEM_TYPE_VALUES.map((value) => ({
        value,
        label: this.dmT("problemType_" + value)
      }))
    },
    problemLevelOptions() {
      return PROBLEM_LEVEL_VALUES.map((value) => ({
        value,
        label: this.dmT("problemLevel_" + value)
      }))
    },
    formRules() {
      return {
        reportTime: [{ required: true, message: this.dmT("ruleReportTimeRequired"), trigger: "change" }],
        villageDeptId: [{ required: true, message: this.dmT("ruleVillageRequired"), trigger: "change" }],
        // problemType: [{ required: true, message: this.dmT("ruleProblemTypeRequired"), trigger: "change" }],
        problemLevel: [{ required: true, message: this.dmT("ruleProblemLevelRequired"), trigger: "change" }],
        problemDetail: [
          { required: true, message: this.dmT("ruleProblemDetailRequired"), trigger: "blur" },
          { max: 2000, message: this.dmT("ruleProblemDetailLen"), trigger: "blur" }
        ],
        handleResult: [{ max: 2000, message: this.dmT("ruleHandleResultLen"), trigger: "blur" }]
      }
    }
  },
  created() {
    this.loadOptions()
    this.getList()
  },
  methods: {
    loadOptions() {
      listThreeAssetsProblemReportTownOptions().then((res) => {
        this.townOptions = Array.isArray(res.data) ? res.data : []
      })
      this.loadVillageTree()
    },
    loadVillageTree() {
      return listThreeAssetsProblemReportVillageTree()
        .then((res) => {
          const raw = res && res.data !== undefined ? res.data : res
          this.villageOptions = flattenVillageOptions(Array.isArray(raw) ? raw : [])
          if (!this.villageOptions.length) {
            this.$modal.msgWarning(this.dmT("villageTreeEmpty"))
          }
        })
        .catch(() => {
          this.villageOptions = []
        })
    },
    formatReportTime(val) {
      if (!val) {
        return this.dash
      }
      return this.parseTime(val) || this.dash
    },
    problemTypeLabel(val) {
      if (!val) {
        return this.dash
      }
      const item = this.problemTypeOptions.find((o) => o.value === val)
      return item ? item.label : val
    },
    problemLevelLabel(val) {
      if (!val) {
        return this.dash
      }
      const item = this.problemLevelOptions.find((o) => o.value === val)
      return item ? item.label : val
    },
    nowReportTime() {
      return this.parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}")
    },
    buildListQuery() {
      const q = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      }
      if (this.queryDateRange && this.queryDateRange.length === 2) {
        q.beginReportTime = this.queryDateRange[0]
        q.endReportTime = this.queryDateRange[1]
      }
      if (this.queryParams.townDeptId != null) {
        q.townDeptId = this.queryParams.townDeptId
      }
      if (this.queryParams.villageDeptId != null) {
        q.villageDeptId = this.queryParams.villageDeptId
      }
      if (this.queryParams.problemType) {
        q.problemType = this.queryParams.problemType
      }
      return q
    },
    getList() {
      this.loading = true
      listThreeAssetsProblemReport(this.buildListQuery())
        .then((res) => {
          this.tableList = res.rows || []
          this.total = res.total || 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryDateRange = null
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        townDeptId: undefined,
        villageDeptId: undefined,
        problemType: undefined,
        beginReportTime: undefined,
        endReportTime: undefined
      }
      this.getList()
    },
    handleAdd() {
      this.dialogEdit = false
      this.formKey += 1
      this.form = createEmptyForm()
      this.form.reportTime = this.nowReportTime()
      this.open = true
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    handleEdit(row) {
      getThreeAssetsProblemReport(row.id).then((res) => {
        this.dialogEdit = true
        this.formKey += 1
        this.form = normalizeForm(res.data)
        if (this.form.reportTime) {
          this.form.reportTime = this.parseTime(this.form.reportTime, "{y}-{m}-{d} {h}:{i}:{s}")
        }
        this.open = true
        this.viewOpen = false
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    handleView(row) {
      getThreeAssetsProblemReport(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleEditFromView() {
      if (!this.viewRow || this.viewRow.id == null) {
        return
      }
      this.handleEdit(this.viewRow)
    },
    handleDelete(row) {
      this.$modal
        .confirm(this.dmT("confirmDelete"))
        .then(() => delThreeAssetsProblemReport(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.dmCommon("msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    buildSubmitPayload() {
      const detail = this.form.problemDetail != null ? String(this.form.problemDetail).trim() : ""
      const handle = this.form.handleResult != null ? String(this.form.handleResult).trim() : ""
      const payload = {
        villageDeptId: this.form.villageDeptId,
        reportTime: this.form.reportTime,
        problemType: this.form.problemType,
        problemLevel: this.form.problemLevel,
        problemDetail: detail,
        handleResult: handle !== "" ? handle : undefined
      }
      if (this.dialogEdit) {
        payload.id = this.form.id
      }
      return payload
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = this.buildSubmitPayload()
        if (this.dialogEdit) {
          updateThreeAssetsProblemReport(payload).then(() => {
            this.$modal.msgSuccess(this.dmCommon("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addThreeAssetsProblemReport(payload).then(() => {
            this.$modal.msgSuccess(this.dmCommon("msgAddOk"))
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
      this.form = createEmptyForm()
    }
  }
}
</script>

<style scoped>
.tapr-section-title {
  margin: 4px 0 12px;
  font-weight: 600;
  color: #303133;
}
.tapr-view-text {
  white-space: pre-wrap;
  word-break: break-all;
}
</style>
