<template>
  <div class="g-main">
    <div class="m-search">
      <el-form
        :inline="true"
        :model="formData"
        ref="ref_searchform"
        :label-width="'100px'"
      >
      <el-form-item label="需求分类" prop="categoryCode">
          <el-cascader
            v-model="formData.categoryCode"
            class="u-item-width-daterange2"
            size="small"
            :options="searchdemandOptions"
            :props="{ checkStrictly: true,label: 'categoryName',value: 'categoryCode',children: 'childCateList'}"
            clearable
            @change="handleCateCHange"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="需求标题" prop="title">
          <el-input
            v-model="formData.title"
            class="u-item-width-normal"
            size="small"
            clearable
            placeholder="请输入"
          >
          </el-input>
        </el-form-item>

        <el-form-item label="需求状态" prop="assignFlag">
          <el-select
            class="u-item-width-normal"
            v-model="formData.assignFlag"
            placeholder="全部"
            size="small"
            clearable
          >
            <el-option
              v-for="item in statusArray"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="timeStart">
          <el-date-picker
            v-model="formData.timeStart"
            class="u-item-width-daterange"
            size="small"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            value="yyyy-MM-dd"
            placeholder="开始时间"
            :picker-options="startPickerOptions"
          >
          </el-date-picker>
          <span class="u-data-tag">至</span>
          <el-date-picker
            v-model="formData.timeEnd"
            class="u-item-width-daterange u-data-tag"
            size="small"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="endPickerOptions"
            value="yyyy-MM-dd"
            placeholder="结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-row type="flex">
          <el-col :span="24" align="right">
            <el-button
              style="margin-left: 30px"
              size="small"
              type="primary "
              @click="handleSearch"
              >查询</el-button
            >
            <el-button
              style="margin-left: 10px"
              is-plain
              class="diy-button--white el-button--default"
              size="small"
              @click="resetSearch"
              >重置</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="m-table">
      <div class="div_btn">
        <el-button
          size="small"
          @click="handleAdd({}, 'add')"
          type="primary"
          icon="el-icon-plus"
        >
          新增</el-button
        >
        <el-button
          @click="handleChu"
          type="primary"
          size="small"
          class="diy-button--white el-button--default"
        >
          导出</el-button
        >
        <el-button @click="deleteBatch" type="primary" size="small">
          批量删除
        </el-button>
      </div>
      <el-table
        ref="gxxq_table"
        border
        :data="tableData"
        v-loading="tableLoading"
        style="width: 100%"
        :height="tableHeight"
        @select-all="selectAll"
        @selection-change="handelSelection"
      >
        <el-table-column
          type="selection"
          fixed="left"
          align="center"
          width="50"
        />
        <el-table-column
          label="需求类别"
          prop="commonServiceTypeName"
          :reserve-selection="true"
          fixed="left"
          align="center"
        />
        <el-table-column
          label="需求标题"
          prop="title"
          fixed="left"
          align="center"
        />

        <el-table-column
          label="指派服务"
          prop="assignFlag"
          fixed="left"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.assignFlag == "0" ? "未指派" : "已指派" }}
          </template>
        </el-table-column>
        <el-table-column
          label="需求发布时间"
          prop="createdTime"
          fixed="left"
          align="center"
        />
        <el-table-column fixed="right" label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button @click="handleEdit(scope.row)" size="small" type="text"
              >查看</el-button
            >
            <el-button
              style="margin-right: 10px"
              @click="handleAdd(scope.row, 'edit')"
              size="small"
              type="text"
              >编辑</el-button
            >
            <template>
              <el-popconfirm
                title="删除之后无法回复，确认删除？"
                @onConfirm="handleDel(scope.row)"
              >
                <el-button size="small" type="text" slot="reference"
                  >删除</el-button
                >
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <div>
        <div class="m-page">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="pageNo"
            :page-sizes="[20, 50, 100, 200]"
            :page-size="pageSize"
            layout="sizes, prev, pager, next, total"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog
      :visible.sync="formShow"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="formTitle"
      destroy-on-close
      width="720px"
      top="5vh"
      class="dialog-h"
      @closed="diaClose"
    >
      <add-form
        v-if="formShow"
        ref="gxxq_form"
        :row-obj="rowObj"
        :formType="formType"
        @handleClose="addFormCancle"
        @handleComfirm="addFormOk"
      ></add-form>
    </el-dialog>
    <el-dialog
      :visible.sync="formEditShow"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="'需求详情'"
      destroy-on-close
      width="900px"
      top="5vh"
      class="dialog-h"
      @closed="diaClose"
    >
      <detail-form
        v-if="formEditShow"
        ref="gxxq_form"
        :commonServiceTypeName="commonServiceTypeName"
        :formType="formType"
        :serviceTypesLevel1="serviceTypesLevel1"
        @handleClose="addFormCancle"
        @handleComfirm="addFormOk"
        :gxxq-id="gxxqId"
      ></detail-form>
    </el-dialog>
  </div>
</template>

<script>
import { requestPost, requestGet } from "@/js/dai/request";
import { mapGetters } from "vuex";
import addForm from "./addForm.vue";
import detailForm from "./detailForm.vue";
import axios from "axios";
export default {
  data() {
    let endDisabledDate = (time) => {
      //这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
      let nowData = Date.now();
      if (this.formData.timeStart) {
        let startTime = new Date(this.formData.timeStart);
        return (
          time.getTime() > nowData ||
          time.getTime() < startTime ||
          time.getTime() === startTime
        );
      } else {
        return time.getTime() > nowData;
      }
    };
    let startDisabledDate = (time) => {
      //这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
      let nowData = Date.now();
      return time.getTime() > nowData;
    };
    return {
      // 公共服务分类
      serviceTypesLevel1: [],
      serviceTypesLevel2: [],
      commonServiceTypeName: "",
      formType: "add",
      formEditShow: false,
      gxxqId: "",
      formData: {
        title: "",
        categoryCode:"",
        parentCategoryCode:"",
        timeStart: "",
        timeEnd: "",
        assignFlag: "",
      },
      statusArray: [
        {
          value: 1,
          label: "已指派服务",
        },
        {
          value: 0,
          label: "未指派服务",
        },
      ],
      endPickerOptions: {
        disabledDate: endDisabledDate,
      },
      startPickerOptions: {
        disabledDate: startDisabledDate,
      },
      selection: [],
      selAllFlag: false,
      tableData: [],
      pageNo: 1,
      pageSize:window.localStorage.getItem('pageSize') || 20,
      tableLoading: true,
      total: 0,
      searchH: 170,
      formShow: false,
      formTitle: "",
      rowObj: {},
      searchdemandOptions:[]
    };
  },
  created() {},
  components: { addForm, detailForm },
  methods: {
    async getCommonDemandList() {
      const url = "/governance/commonDemand/list";
      let params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        ...this.formData,
      };
      let { data, msg, code } = await requestPost(url, params);
      this.tableLoading = false;
      if (code == 0) {
        this.tableData = data.list;
        this.total = data.total;
      } else {
        this.$message.error(msg);
      }
    },
    addFormCancle() {
      this.formShow = false;
      this.formEditShow = false;
    },
    handelSelection(row) {
      this.selection = row;
    },
    addFormOk() {
      this.formShow = false;
      this.formEditShow = false;
      this.getCommonDemandList();
    },
    selectAll(selection) {
      this.selection = selection;
      if (selection.length > 0) {
        this.selAllFlag = true;
      } else {
        this.selAllFlag = false;
      }
    },
    handleAdd(row, type) {
      if (type == "add") {
        this.formTitle = "添加需求";
        this.formShow = true;
        this.formType = "add";
      } else {
        this.formTitle = "修改需求";
        this.formShow = true;
        console.log(row);
        this.rowObj = row;
        this.$nextTick(() => {
          this.$refs.gxxq_form.initForm(type, row);
        });
      }
    },
    handleEdit(row) {
      this.gxxqId = row.id;
      this.commonServiceTypeName = row.commonServiceTypeName;
      this.serviceTypesLevel1 = this.serviceTypesLevel1;
      this.formEditShow = true;
    },
    async handleChu() {
      const url = "/governance/commonDemand/export";
      const { pageSize, pageNo, formData } = this;
      axios({
        url: window.SITE_CONFIG["apiURL"] + url,
        method: "post",
        data: {
          pageSize,
          pageNo,
          ...formData,
        },
        responseType: "blob",
      })
        .then((res) => {
          let fileName = window.decodeURI(
            res.headers["content-disposition"].split(";")[1].split("=")[1]
          );
          console.log("filename", fileName);
          let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
          var url = window.URL.createObjectURL(blob);
          var aLink = document.createElement("a");
          aLink.style.display = "none";
          aLink.href = url;
          aLink.setAttribute("download", fileName);
          document.body.appendChild(aLink);
          aLink.click();
          document.body.removeChild(aLink); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        })
        .catch((err) => {
          console.log("获取导出情失败", err);
          return this.$message.error("网络错误");
        });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.getCommonDemandList();
    },
    async handleDel(row) {
      const url = `/governance/commonDemand/delete/`;
      let { code, msg } = await requestPost(url, [row.id]);
      if (code == 0) {
        this.$message.success("删除成功");
      } else if (code >= 8000) {
        this.$message.error(msg);
      }
      this.getCommonDemandList();
    },
    handleSearch() {
      console.log(this.formData);
      this.getCommonDemandList();
    },
    resetSearch() {
      this.formData = {
        title: "",
        categoryCode:"",
        parentCategoryCode:"",
        timeStart: "",
        timeEnd: "",
        assignFlag: "",
      };

      this.pageNo = 1;
      this.getCommonDemandList();
    },
    handleCurrentChange(val) {
      this.pageNo = val;
      this.getCommonDemandList();
    },
    diaClose() {
      this.formShow = false;
    },
    // checkSelectable(row, index) {
    //     console.log(index);
    //   return row.id;
    // },
    async deleteresiBatch() {
      if (this.selection.length === 0)
        return this.$message.error("请选择之后进行操作");
      let ids = this.selection.map((item) => item.id);
      this.$http
        .post("/governance/commonDemand/delete/", ids)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.$message.success("删除成功");
            this.getCommonDemandList();
          }
        })
        .catch((err) => {
          console.log("row4", err);
          return this.$message.error("网络错误");
        });
    },
    deleteBatch() {
      if (this.selection.length > 0) {
        this.$confirm("删除之后无法恢复，确认删除？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.deleteresiBatch();
          })
          .catch((err) => {
            if (err == "cancel") {
            }
          });
      } else {
        this.$message.warning("请先选择要删除的需求");
      }
    },
    // 获取服务组织
    async getDictOptions() {
      this.$http
        .get("/governance/commonServiceType/selectList/0")
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.serviceTypesLevel1 = res.data;
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });
    },
    handleCateCHange(val) {
      if (val.length === 1) {
        this.searchdemandOptions.forEach((item) => {
          if (item.value == val[0]) this.formData.parentCategoryCode = item.pvalue;
        });
        this.formData.categoryCode = val[0];
      } else {
        this.formData.parentCategoryCode = val[0];
        this.formData.categoryCode = val[1];
      }
    },
    async getDemandOptions() {
      this.$http
        .post("/actual/base/serviceitem/listAllCategory")
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.searchdemandOptions = this.getTreeData(res.data);
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });
    },
    getTreeData(data) {
      if (!Array.isArray(data)) return [];
      let arr = data.map((item) => {
        let _item = {};
        if (item.childCateList) {
          if (item.childCateList.length === 0)
            _item = { ...item, childCateList: undefined };
          else _item = { ...item, childCateList: this.getTreeData(item.childCateList) };
        } else {
          _item = { ...item };
        }
        return _item;
      });
      return arr;
    },
  },
  mounted() {
    this.getCommonDemandList();
    this.getDictOptions();
    this.getDemandOptions()
  },
  computed: {
    ...mapGetters(["clientHeight", "iframeHeight"]),
    tableHeight() {
      const h = this.clientHeight - this.searchH - 275 + this.iframeHeight;
      const _h = this.clientHeight - 275 - this.searchH;
      return this.$store.state.inIframe ? h : _h;
    },
  },
  watch: {
    "formData.timeEnd": function (val) {
      if (val && val != "") {
        let arrayTemp = val.split(" ");
        this.formData.timeEnd = arrayTemp[0] + " 23:59:59";
      }
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/scss/modules/management/list-main.scss";
.div_btn {
  margin-bottom: 12px;
}
</style>
