<template>
  <div class="div_main">
    <div>
      <div class="div_search">
        <el-form :inline="true"
                 :model="formData"
                 ref="ref_searchform"
                 :label-width="'80px'">
          <div>

            <el-form-item label="政策标题"
                          prop="title">
              <el-input v-model="formData.title"
                        class="item_width_1"
                        size="small"
                        clearable
                        placeholder="请输入">
              </el-input>
            </el-form-item>

            <el-form-item label="政策内容"
                          prop="content">
              <el-input v-model="formData.content"
                        class="item_width_2"
                        size="small"
                        clearable
                        placeholder="请输入">
              </el-input>
            </el-form-item>

            <el-form-item label="是否过期"
                          prop="expiredFlag">
              <el-select class="item_width_2"
                         v-model="formData.expiredFlag"
                         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="div_table">

        <div class="div_btn">
          <el-button class="diy-button--add"
                     size="small"
                     @click="handleAdd">新增政策</el-button>

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

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

          <el-table-column prop="policyLevelName"
                           label="政策级别"
                           width="100"
                           align="center"
                           :show-overflow-tooltip="true">
          </el-table-column>

          <el-table-column prop="title"
                           align="center"
                           min-width="150"
                           label="政策标题"
                           :show-overflow-tooltip="true">

          </el-table-column>
          <el-table-column prop="content"
                           align="center"
                           min-width="250"
                           label="政策内容"
                           :show-overflow-tooltip="true">

          </el-table-column>

          <el-table-column prop="serviceTimeStart"
                           align="center"
                           width="300"
                           :show-overflow-tooltip="true"
                           label="政策时间">
            <template slot-scope="scope">
              <span>{{scope.row.startDate}}-{{scope.row.endDate}}</span>
            </template>
          </el-table-column>

          <el-table-column prop="expiredFlag"
                           align="center"
                           width="100"
                           label="是否过期"
                           :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{scope.row.expiredFlag==='1'?'已过期':'未过期'}}</span>
            </template>
          </el-table-column>

          <el-table-column fixed="right"
                           label="操作"
                           align="center"
                           width="180">
            <template slot-scope="scope">
              <el-button @click="handleDetail(scope.row)"
                         type="text"
                         size="small"
                         class=".div-table-button--detail">详情</el-button>
              <el-button @click="handleEdit(scope.row)"
                         type="text"
                         size="small"
                         class="div-table-button--edit">编辑</el-button>
              <el-button @click="handlePersonList(scope.row)"
                         type="text"
                         size="small"
                         class="div-table-button--edit">人员名单</el-button>
              <el-button @click="handleDel(scope.row)"
                         type="text"
                         size="small"
                         class="div-table-button--delete">删除</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>
    <el-dialog v-if="showAdd"
               :visible.sync="showAdd"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="addDiaTitle"
               :modal-append-to-body="false"
               width="1050px"
               top="5vh"
               class="dialog-h"
               @closed="showAdd = false">
      <add-policy ref="ref_add_form"
                  :formType="formType"
                  :policyId="policyId"
                  @handleOk="handleOk"
                  @handleClose="handleClose"></add-policy>
    </el-dialog>
    <el-dialog v-if="showPersonList"
               :visible.sync="showPersonList"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="'人员名单'"
               width="1150px"
               top="5vh"
               class="dialog-h"
               @closed="showPersonList = false">
      <person-list ref="ref_detail_form"
                   :policyId="policyId"
                   :ruleList="ruleList"
                   @handleOk="handleOk"
                   @handleClose="handleClose"
                   :formType="formType">
      </person-list>
    </el-dialog>

  </div>
</template>

<script>
import { requestPost } from "@/js/dai/request";
import nextTick from "dai-js/tools/nextTick";
import { mapGetters } from "vuex";
// import eventInfo from "./cpts/event-info";
import axios from "axios";
import addPolicy from "./addPolicy";
import personList from "./personList";


export default {
  components: { addPolicy, personList },

  data () {


    return {
      tableLoading: false,
      user: {},
      agencyId: '',

      tableData: [],

      statusArray: [
        {
          value: "1",
          label: "是",
        },
        {
          value: "0",
          label: "否",
        },
      ],


      formData: {
        title: '',//	政策标题	
        content: '',//政策内容		
        expiredFlag: '',//是否过期；1：已过期；0：未过期	

      },
      pageNo: 1,
      pageSize: window.localStorage.getItem("pageSize") || 20,
      total: 1,

      policyId: '',
      serviceProjectName: '',

      showAdd: false,

      formType: 'add',
      addDiaTitle: '新增政策',

      showPersonList: false,
      ruleList: []


    };
  },
  computed: {
    maxTableHeight () {
      return this.$store.state.inIframe
        ? this.clientHeight - 350 + this.iframeHeigh
        : this.clientHeight - 350;
    },
    ...mapGetters(["clientHeight", "iframeHeight"]),
  },
  watch: {

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

    this.getTableData();
  },
  methods: {

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

    async handleAdd () {
      this.addDiaTitle = '新增政策'
      this.formType = 'add'
      this.showAdd = true;
    },

    async handleDetail (row) {
      this.policyId = row.policyId
      this.addDiaTitle = '政策详情'
      this.formType = 'detail'
      this.showAdd = true

    },
    async handleEdit (row) {
      this.policyId = row.policyId
      this.addDiaTitle = '编辑政策'
      this.formType = 'edit'
      this.showAdd = true;

    },

    //加载组织数据
    async handlePersonList (row) {

      this.policyId = row.policyId
      await this.loadRuleList()
      this.formType = 'personList'
      this.showPersonList = true;
    },

    async loadRuleList () {

      const url = "/heart/policy/rulelist/" + this.policyId

      let params = {}

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

      if (code === 0) {
        this.ruleList = data

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

    },


    handleClose () {
      this.policyId = ""
      this.formType = ''

      this.showAdd = false
      this.showPersonList = false



    },
    handleOk () {
      this.handleClose()
      this.pageNo = 1
      this.getTableData()

    },


    async handleDel (row) {

      this.policyId = row.policyId

      this.$confirm("确认删除政策?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.delPolicy()
        })
        .catch(err => {
          if (err == "cancel") {
            // this.$message({
            //   type: "info",
            //   message: "已取消删除"
            // });
          }
        });

    },

    async delPolicy () {

      const url = `/heart/policy/delete/${this.policyId}`;

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

      if (code === 0) {
        this.$message.success("删除成功！");
        this.getTableData();
      } else {
        this.$message.error("操作失败！");
      }
    },

    async getTableData () {
      this.tableLoading = true
      const url = "/heart/policy/list";
      // const url = "http://yapi.elinkservice.cn/mock/245/heart/icServiceProject/service/recordList";
      const { pageSize, pageNo, formData } = this;
      const { data, code, msg } = await requestPost(url, {
        pageSize,
        pageNo,
        ...formData,
      });

      this.tableLoading = false
      if (code === 0) {

        this.total = data.total || 0;
        this.tableData = data.list
          ? data.list.map((item) => {
            return item;
          })
          : [];

        this.tableData.forEach(item => {
          if (item.operationType === '2') {
            item.operationTypeShow = '已转需求'
          }
          if (item.operationType === '1') {
            item.operationTypeShow = '已立项'
          }
          if (item.operationType === '0') {
            item.operationTypeShow = '已回复'
          }

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

    async handleExport () {
      const url = "/gov/project/icEvent/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) {

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

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

    resetSearch () {
      this.formData = {
        title: '',//	政策标题	
        content: '',//政策内容		
        expiredFlag: '',//是否过期；1：已过期；0：未过期	
      }


      this.pageNo = 1
      this.getTableData()
    },
  },
};
</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";
</style>
