<template>
  <div class="g-main">
    <div v-show="pageType == 'list'">
      <div class="m-search">
        <el-form :inline="true"
                 :model="formData"
                 ref="ref_searchform"
                 :label-width="'90px'">
          <div>

            <el-form-item label="所属组织"
                          prop="orgId">
              <el-cascader class="item_width_2"
                           ref="myCascader"
                           size="small"
                           v-model="agencyIdArray"
                           :options="orgOptions"
                           :props="orgOptionProps"
                           :show-all-levels="false"
                           @change="handleChangeAgency"></el-cascader>

            </el-form-item>

            <el-form-item label="议题标题"
                          prop="issueTitle">
              <el-input v-model="formData.issueTitle"
                        class="item_width_2"
                        size="small"
                        clearable
                        placeholder="请输入">
              </el-input>
            </el-form-item>

            <el-form-item label="转议题时间"
                          prop="startTime">
              <el-date-picker v-model="formData.startTime"
                              :picker-options="startPickerOptions"
                              class="item_width_2"
                              size="small"
                              type="date"
                              value-format="yyyyMMdd"
                              value="yyyy-MM-dd"
                              placeholder="开始时间">
              </el-date-picker>
              <span class="u-data-tag">至</span>
              <el-date-picker v-model="formData.endTime"
                              :picker-options="endPickerOptions"
                              class="item_width_2 u-data-tag"
                              size="small"
                              type="date"
                              value-format="yyyyMMdd"
                              value="yyyy-MM-dd"
                              placeholder="结束时间">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="状态"
                          prop="applyStatus">
              <el-select class="item_width_2"
                         v-model="formData.applyStatus"
                         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-button style="margin-left:30px"
                       size="small"
                       class="diy-button--search"
                       @click="handleSearch">查询</el-button>
            <el-button style="margin-left:10px"
                       size="small"
                       class="diy-button--reset"
                       @click="resetSearch">重置</el-button>
          </div>
        </el-form>
      </div>

      <div class="m-table">

        <div class="div_btn">

          <el-button @click="handleExport"
                     class="diy-button--reset"
                     size="small">导出</el-button>

        </div>

        <el-table :data="tableData"
                  border
                  :header-cell-style="{background:'#2195FE',color:'#FFFFFF'}"
                  class="table"
                  style="width: 100%"
                  :height="maxTableHeight">
          <el-table-column label=""
                           fixed="left"
                           type="selection"
                           align="center"
                           width="50" />
          <el-table-column label="序号"
                           fixed="left"
                           type="index"
                           align="center"
                           width="50" />

          <el-table-column prop="gridName"
                           align="center"
                           label="所属网格"
                           :show-overflow-tooltip="true">
          </el-table-column>

          <el-table-column prop="issueTitle"
                           label="议题标题"
                           min-width="150"
                           align="center"
                           :show-overflow-tooltip="true">
          </el-table-column>

          <el-table-column prop="suggestion"
                           align="center"
                           min-width="150"
                           label="处理建议"
                           :show-overflow-tooltip="true">
          </el-table-column>

          <el-table-column prop="applyTime"
                           align="center"
                           width="180"
                           :show-overflow-tooltip="true"
                           label="提交审核时间">
          </el-table-column>

          <el-table-column prop="applyStatusName"
                           align="center"
                           label="状态"
                           width="80"
                           :show-overflow-tooltip="true">

          </el-table-column>

          <el-table-column fixed="right"
                           label="操作"
                           align="center"
                           width="100">
            <template slot-scope="scope">

              <el-button v-if="scope.row.applyStatus==='under_auditing'"
                         @click="handleAudit(scope.row)"
                         type="text"
                         size="small"
                         class="div-table-button--edit">审核</el-button>

              <el-button @click="handleWatch(scope.row)"
                         type="text"
                         size="small">查看</el-button>

            </template>
          </el-table-column>
        </el-table>

        <div>
          <el-pagination @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"
                         :current-page.sync="pageNo"
                         :page-sizes="[20, 50, 100, 200]"
                         :page-size="parseInt(pageSize)"
                         layout="sizes, prev, pager, next, total"
                         :total="total">
          </el-pagination>
        </div>

      </div>

    </div>
    <div v-if="pageType == 'dispose' || pageType == 'info'">
      <issue-info ref="eleEditForm"
                  :pageType="pageType"
                  :issueId="issueId"
                  :issueDetailData="issueDetailData"
                  @handleClose="handleClose"
                  @handleOk="handleOk"
                  @dialogOk="handleEditSuccess" />
    </div>

  </div>
</template>

<script>
import { requestPost } from "@/js/dai/request";
import nextTick from "dai-js/tools/nextTick";
import { mapGetters } from "vuex";
import issueInfo from "./cptsAudit/issue-info";
import axios from "axios";

export default {
  components: { issueInfo },

  data () {
    let endDisabledDate = (time) => {//这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
      let nowData = Date.now()
      if (this.formData.startTime) {
        let startTime = new Date(this.formData.startTime)
        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 {
      pageType: "list", // 列表list 新增add  处理dispose 详情info
      user: {},
      agencyId: '',
      gridList: [],//所属网格list--场所区域
      tableData: [],

      statusArray: [
        {
          value: "under_auditing",
          label: "待审核",
        },
        {
          value: "rejected",
          label: "驳回",
        },

      ],


      formData: {
        orgId: '',
        orgType: '',
        issueTitle: '',
        startTime: '',
        endTime: '',
        applyStatus: '',
      },
      orgOptions: [],
      orgOptionProps: {
        multiple: false,
        value: 'agencyId',
        label: 'agencyName',
        children: 'subAgencyList',
        checkStrictly: true
      },
      agencyIdArray: [],

      pageNo: 1,
      pageSize: window.localStorage.getItem("pageSize") || 20,
      total: 1,
      endPickerOptions: {
        // disabledDate: endDisabledDate
      },
      startPickerOptions: {
        // disabledDate: startDisabledDate
      },
      issueId: '',
      issueDetailData: {},

    };
  },
  computed: {
    maxTableHeight () {
      return this.$store.state.inIframe
        ? this.clientHeight - 360 + this.iframeHeigh
        : this.clientHeight - 360;
    },
    ...mapGetters(["clientHeight", "iframeHeight"]),
  },
  watch: {
    "formData.endTime": function (val) {
      if (val && val != '') {
        let arrayTemp = val.split(' ')
        this.formData.endTime = arrayTemp[0] + ' 23:59:59'
      }

    },
  },
  mounted () {
    console.log(this.$store.state)
    this.user = this.$store.state.user

    this.agencyId = this.user.agencyId
    this.getOrgTreeList();
    this.getTableData();

  },
  methods: {

    handleSearch (val) {
      console.log(this.formData);
      this.pageNo = 1;
      this.getTableData();
    },

    handleChangeAgency (val) {
      let obj = this.$refs["myCascader"].getCheckedNodes()[0].data

      if (obj) {
        this.formData.orgType = obj.level === 'grid' ? 'grid' : 'agency'
        this.formData.orgId = obj.agencyId

      } else {
        this.form.orgType = ''
        this.form.orgId = ''
      }


    },

    async getOrgTreeList () {
      const url = "/gov/org/customeragency/agencygridtree"

      let params = {
        agencyId: this.agencyId,
        purpose: "query"
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.orgOptions = []
        this.orgOptions.push(data)

      } else {
        this.$message.error(msg)
      }

    },

    async handleExport () {
      const url = "/gov/issue/issueaudit/auditListExport";
      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("网络错误");
        });
    },

    async handleWatch (row) {
      this.issueId = row.issueApplicationId

      const url = "/gov/issue/issueaudit/applicationdetail";
      // const url = "http://yapi.elinkservice.cn/mock/245/gov/project/icEvent/detail";

      const { data, code, msg } = await requestPost(url, {
        issueApplicationId: this.issueId,
      });

      if (code === 0) {

        this.issueDetailData = { ...data };
        this.pageType = "info";
      } else {
        this.$message.error(msg);
      }
    },

    //加载组织数据
    async handleAudit (row) {
      this.issueId = row.issueApplicationId

      const url = "/gov/issue/issueaudit/applicationdetail";
      // const url = "http://yapi.elinkservice.cn/mock/245/gov/project/icEvent/detail";

      const { data, code, msg } = await requestPost(url, {
        issueApplicationId: this.issueId,
      });

      if (code === 0) {

        this.issueDetailData = { ...data };
        this.pageType = "dispose";
      } else {
        this.$message.error(msg);
      }
    },

    handleClose () {
      this.pageType = "list";
      this.issueId = ""
      this.getTableData()

    },
    handleOk () {
      this.pageType = "list";
      this.issueId = ""
      this.pageNo = 1
      this.getTableData()

    },

    handleEditSuccess () {
      this.handleClose();
      this.getTableData();
    },



    async getTableData () {
      const url = "/gov/issue/issueaudit/auditList";

      const { pageSize, pageNo, formData } = this;
      const { data, code, msg } = await requestPost(url, {
        pageSize,
        pageNo,
        ...formData,
      });
      if (code === 0) {

        this.total = data.total || 0;
        this.tableData = data.list
          ? data.list.map((item) => {
            return item;
          })
          : [];
      } else {
        this.$message.error(msg);
      }
    },


    handleSizeChange (val) {

      this.pageSize = val;
      window.localStorage.setItem("pageSize", val);
      this.getTableData();
    },
    handleCurrentChange (val) {

      this.pageNo = val;
      this.getTableData();
    },

    resetSearch () {
      this.agencyIdArray = []
      this.formData = {
        orgId: '',
        orgType: '',
        issueTitle: '',
        startTime: '',
        endTime: '',
        applyStatus: '',

      }

      this.pageNo = 1
      // this.getTableData();

    },
    deepTree (arr, child) {
      if (Array.isArray(arr) && arr.length > 0) {
        return arr.map(item => {
          // if (child === 'subAgencyList') item.value = item.orgType + '-' + item.orgId
          return {
            ...item,
            [child]: item[child] && item[child].length > 0 && this.deepTree(item[child], child) || null
          }
        })
      }
    }
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/scss/buttonstyle.scss";
@import "@/assets/scss/modules/management/list-main.scss";
@import "@/assets/scss/modules/shequzhili/event-info.scss";
.m-search {
  .item_width_2 {
    width: 200px;
  }
}
</style>
