<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="企业名称" prop="enterpriseName">
        <el-input
          v-model="queryParams.enterpriseName"
          placeholder="请输入企业名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="停气类型" prop="fStopType">
        <el-select v-model="queryParams.fStopType" placeholder="请选择停气类型" clearable size="small">
          <el-option
            v-for="dict in fStopTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="停气进度" prop="fStopProgress">
        <el-select v-model="queryParams.fStopProgress" placeholder="请选择停气进度" clearable size="small">
          <el-option
            v-for="dict in fStopProgressOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上报状态" prop="fRepStatus" v-if="-2 != $store.state.user.enterpriseId">
        <el-select v-model="queryParams.fRepStatus" placeholder="请选择上报状态" clearable size="small">
          <el-option label="未上报" value="0" />
          <el-option label="已上报" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="上报状态" prop="fGovUploadStatus" v-if="-2 == $store.state.user.enterpriseId">
        <el-select v-model="queryParams.fGovUploadStatus" placeholder="请选择上报状态" clearable size="small">
          <el-option label="未上报" value="0" />
          <el-option label="已上报" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @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="el-icon-plus"
          size="mini"
          v-if="-2 != $store.state.user.enterpriseId"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
     <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		      :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="supList">
     <!-- <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="企业名称" align="center" prop="enterpriseName" :show-overflow-tooltip="true"/>
      <el-table-column label="停气开始日期" align="center" prop="fStartDate" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.fStartDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="停气结束日期" align="center" prop="fEndDate" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.fEndDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="停气类型" align="center" prop="fStopType" :formatter="fStopTypeFormat" />
      <el-table-column label="影响用户" align="center" prop="fInfluenceCus" />
      <el-table-column label="停气进度" align="center" prop="fStopProgress" :formatter="fStopProgressFormat" />
      <el-table-column label="恢复供气时间" align="center" prop="fRecoveryGasTime" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.fRecoveryGasTime">{{ parseTime(scope.row.fRecoveryGasTime, '{y}-{m}-{d}') }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="上报状态" align="center" prop="fRepStatus" v-if="this.$store.state.user.roleId == 5">
        <template slot-scope="scope">
          <span v-if="scope.row.fRepStatus == '0'">未上报</span>
          <span v-else-if="scope.row.fRepStatus == '1'">已上报</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="上报时间" align="center" prop="entRepTime" width="150" v-if="this.$store.state.user.roleId == 5">
        <template slot-scope="scope">
          <span v-if="scope.row.entRepTime">{{ parseTime(scope.row.entRepTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="上报省厅状态" align="center" prop="fGovUploadStatus" v-if="this.$store.state.user.roleId == 3">
        <template slot-scope="scope">
          <span v-if="scope.row.fGovUploadStatus == '0'">未上报</span>
          <span v-else-if="scope.row.fGovUploadStatus == '1'">已上报</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="上报省厅时间" align="center" prop="fRecoveryGasTime" width="150" v-if="this.$store.state.user.roleId == 3">
        <template slot-scope="scope">
          <span v-if="scope.row.fGovUploadTime">{{ parseTime(scope.row.fGovUploadTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.fRepStatus == '0'"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-if="scope.row.fRepStatus == '0'"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleReport(scope.row)"
          >上报</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.fRepStatus == '1' && -2 != $store.state.user.enterpriseId"
            @click="handleStop(scope.row)"
          >停气状态</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-dialog :title="title" :visible.sync="open" v-if="open" width="1200px" append-to-body :close-on-click-modal="false">
      <el-form label-position="top" ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-row class="el-row-table">
              <el-col :span="12">
                <el-form-item label="停气开始日期" prop="fStartDate">
                  <el-date-picker clearable size="small"
                                  v-model="form.fStartDate"
                                  type="datetime"
                                  value-format="yyyy-MM-dd HH:mm:ss"
                                  style="width: 98%"
                                  placeholder="选择停气开始日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="停气结束日期" prop="fEndDate">
                  <el-date-picker clearable size="small"
                                  v-model="form.fEndDate"
                                  type="datetime"
                                  value-format="yyyy-MM-dd HH:mm:ss"
                                  style="width: 100%"
                                  placeholder="选择停气结束日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="停气类型" prop="fStopType">
                  <el-select v-model="form.fStopType" style="width: 98%" placeholder="请选择停气类型">
                    <el-option
                      v-for="dict in fStopTypeOptions"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <!--<el-col :span="12">
                <el-form-item label="停气进度" prop="fStopProgress">
                  <el-select v-model="form.fStopProgress" style="width: 98%" placeholder="请选择停气进度">
                    <el-option
                      v-for="dict in fStopProgressOptions"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>-->

              <el-col :span="12">
                <el-form-item label="影响用户" prop="fInfluenceCus">
                  <el-input type="Number" v-model="form.fInfluenceCus" placeholder="请输入影响用户" />
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="停气原因" prop="fStopReason">
                  <el-input type="textarea" v-model="form.fStopReason" placeholder="请输入停气原因" />
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="停气范围" prop="fStopRange">
                  <el-input type="textarea" v-model="form.fStopRange" placeholder="请输入停气范围" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>

          <el-col :span="12" style="padding-left: 10px">
            <el-form-item label="停气区域" prop="fGasStopArea">
              <DrawArea class="area-change" v-model="path" @update-path="handleUpdatePathFromParent"/>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm()">保 存</el-button>
        <!--<el-button @click="submitForm()">上 报</el-button>-->
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 停气状态弹框 -->
    <el-dialog title="停气状态" :visible.sync="stopOpen" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="stopForm" :model="stopForm" :rules="stopRules" label-width="120px">
        <el-form-item label="停气进度" prop="fStopProgress">
          <el-select v-model="stopForm.fStopProgress" style="width: 98%" placeholder="请选择停气进度">
            <el-option
              v-for="dict in fStopProgressOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitStopForm()">保 存</el-button>
        <!--<el-button @click="submitForm()">上 报</el-button>-->
        <el-button @click="stopOpen=false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情 -->
    <DetailInfo ref="detail"/>

  </div>
</template>

<script>
import { listSup, getSup, delSup, addSup, updateSup, exportSup, reportSupBalStopSupRecInfo, changeStopStatus } from "@/api/supplybalance/stop";
// 如果只允许画一个，则用这个
// import DrawArea from "@/components/DrawArea";
// 如果需要画多个，则用这个
import DrawArea from "@/components/GasShutDownDrawArea"
import DetailInfo from "./components/DetailInfo";
import moment from "moment";
export default {
  name: "Sup",
  components: {
    DrawArea,
    DetailInfo
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 停气监管表格数据
      supList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 停气类型字典
      fStopTypeOptions: [],
      // 停气进度字典
      fStopProgressOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fCompanyInfoId: null,
        fStopType: null,
        fStopProgress: null,
        fRepStatus: null,
        enterpriseName: null,
        fGovUploadStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        fStartDate: [
          { required: true, message: "停气开始日期不能为空", trigger: "blur" }
        ],
        fEndDate: [
          { required: true, message: "停气结束日期不能为空", trigger: "blur" }
        ],
        fStopType: [
          { required: true, message: "停气类型不能为空", trigger: "change" }
        ],
        fInfluenceCus: [
          { required: true, message: "影响用户不能为空", trigger: "blur" }
        ],
        fStopRange: [
          { required: true, message: "停气范围不能为空", trigger: "blur" }
        ],
        fStopProgress: [
          { required: true, message: "停气进度不能为空", trigger: "change" }
        ],
        fGasStopArea: [
          { required: true, message: "停气区域不能为空" }
        ],
      },
      path:[
        [114.602763,38.071221],
        [114.762751,38.056354],
        [114.657695,38.020932],
        [114.655978,38.020121]
      ],
      stopOpen: false,
      stopForm: {},
      stopRules: {
        fStopProgress: [
          { required: true, message: "停气进度不能为空", trigger: "change" }
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("t_stop_type").then(response => {
      this.fStopTypeOptions = response.data;
    });
    this.getDicts("t_stop_progress").then(response => {
      this.fStopProgressOptions = response.data;
    });
  },
  watch:{
    path(newVal,oldVal){
      console.log("index.watch.path = " + newVal);
      // 如果只允许画一个多边形，则用这个方法接收数据
      // if(newVal.length == 0){
      //   this.form.fGasStopArea = "";
      //   return
      // }
      // this.form.fGasStopArea = JSON.stringify(newVal);

    }
  },
  methods: {
    // 需要画多个 多边形时 需要正确使用 emit 接收 drawArea 发回来的数据
    handleUpdatePathFromParent(data) {

      // 如果需要画多个则，需要这样接数据
      if(data.length === 0) {
        this.form.fGasStopArea = "";
        return
      }

      this.form.fGasStopArea = "";
      for(let i = 0;i < data.length;i ++) {
        let newValItem = data[i];
        if (newValItem._opts) {
          this.form.fGasStopArea += JSON.stringify(newValItem._opts.path) + "#";
        } else {
          this.form.fGasStopArea += JSON.stringify(newValItem) + "#";
        }
        console.log("this.form.fGasStopArea = " + this.form.fGasStopArea);
      }
    },
    /** 查询停气监管列表 */
    getList() {
      this.loading = true;
      listSup(this.queryParams).then(response => {
        this.supList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 停气类型字典翻译
    fStopTypeFormat(row, column) {
      return this.selectDictLabel(this.fStopTypeOptions, row.fStopType);
    },
    // 停气进度字典翻译
    fStopProgressFormat(row, column) {
      return this.selectDictLabel(this.fStopProgressOptions, row.fStopProgress);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fGasStopId: null,
        fCompanyInfoId: null,
        fStartDate: null,
        fEndDate: null,
        fStopType: null,
        fInfluenceCus: null,
        fStopReason: null,
        fStopRange: null,
        fStopProgress: null,
        fRecoveryGasTime: null,
        fRepStatus: "0",
        fGasStopArea: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDel: null,
        remarks: null
      };
      this.resetForm("form");
      this.path = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fGasStopId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加停气监管";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const fGasStopId = row.fGasStopId || this.ids
      getSup(fGasStopId).then(response => {
        this.form = response.data;
        if(this.form.fGasStopArea){
          console.log("this.from.fGasStopArea = " + this.form.fGasStopArea);
          let areasArr = [];
          if (this.form.fGasStopArea.includes("#")){
            let areas = this.form.fGasStopArea.split("#");
            for (let i = 0; i < areas.length;i++) {
              console.log("i = " + i+  "item = " + areas[i]);
              let areasItem = areas[i];
              if (areasItem != null && areasItem != "") {
                areasArr.push(JSON.parse(areasItem))
              }
            }
            this.path = areasArr;
            console.log("this.path = " + this.path);
          } else{
            areasArr.push( this.form.fGasStopArea);
            this.path = areasArr;
          }
        }
        this.open = true;
        this.title = "修改停气监管";
      });
    },
    /** 提交按钮 */
    submitForm() {
      /*if(1 == type){
        this.form.fRepStatus = '1';
      }*/
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.fGasStopId != null) {
            updateSup(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSup(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fGasStopIds = row.fGasStopId || this.ids;
      this.$confirm('是否确认删除停气监管编号为"' + fGasStopIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delSup(fGasStopIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有停气监管数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportSup(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    //详情
    handleDetail(row){
      this.$refs.detail.getDetailInfo(row.fGasStopId);
    },
    handleReport(row) {
      const that = this;
      this.$confirm('是否确认上报停气监管编号为"' + row.fGasStopId + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        if(-2 == that.$store.state.user.enterpriseId){
          return reportSupBalStopSupRecInfo({fGasStopId : row.fGasStopId});
        }
        return updateSup({fGasStopId : row.fGasStopId,fRepStatus : '1',entRepTime: moment().format('YYYY-MM-DD HH:mm:ss')});
      }).then(() => {
        this.getList();
        this.msgSuccess("上报成功");
      }).catch(() => {});
    },
    handleStop(row){
      getSup(row.fGasStopId).then(res => {
        if(res.code == 200 && res.data){
          this.stopForm = res.data;
          this.stopOpen = true;
        }
      })
    },
    submitStopForm(){
      changeStopStatus({fGasStopId:this.stopForm.fGasStopId,fStopProgress:this.stopForm.fStopProgress}).then(res =>{
        if(res.code == 200){
          this.msgSuccess("停气进度更新成功");
          this.stopOpen = false;
          this.getList();
        }
      })
    }
  }
};
</script>
<style lang="scss">
  .area-change input{
    border: 1px solid #DCDFE6 !important;
  }
</style>
