<template>
  <div class="manage-container">
    <div class="manage-wrap" style="height: 40px">
      <div class="manage-input">
        <el-form ref="form" :model="queryForm" label-width="100px">
          <vab-query-form>
            <el-form-item width="100" prop="month" label="时间选择">
              <el-date-picker
                v-model="date"
                size="small"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="standardToTime"
              ></el-date-picker>
            </el-form-item>
          </vab-query-form>
        </el-form>
      </div>
      <div>
        <el-button type="primary" size="small" @click="init">
          {{ $t('defalult.cx') }}
        </el-button>
      </div>
    </div>
    <div style="padding: 10px; border: 1px solid #ebeef5; margin: 10px 0">
      <div style="float: left; margin-right: 10px">配置显示项:</div>
      <el-checkbox-group v-model="checkList">
        <el-checkbox v-for="item in deviceList" :label="item.deviceId">
          {{ item.deviceName }}
        </el-checkbox>
      </el-checkbox-group>
    </div>
    <el-button type="primary" @click="add">新增</el-button>
    <el-table
      :data="tableData"
      v-loading="listLoading"
      style="width: 100%; margin: 10px 0"
    >
      <el-table-column align="center" label="基础项">
        <el-table-column :label="$t('defalult.rq')" width="120">
          <template #default="{ row }">
            {{ row.basic['date'] }}
          </template>
        </el-table-column>

        <el-table-column label="进水COD" width="100">
          <template #default="{ row }">
            {{ row.basic['inCod'] }}
          </template>
        </el-table-column>
        <el-table-column label="进水氨氮" width="100">
          <template #default="{ row }">
            {{ row.basic['inAn'] }}
          </template>
        </el-table-column>
        <el-table-column label="进水TN" width="100">
          <template #default="{ row }">
            {{ row.basic['inTn'] }}
          </template>
        </el-table-column>
        <el-table-column label="进水TP" width="100">
          <template #default="{ row }">
            {{ row.basic['inTp'] }}
          </template>
        </el-table-column>
      </el-table-column>
      <template v-for="item in deviceList">
        <el-table-column
          align="center"
          v-if="checkList.includes(item.deviceId)"
          :label="item.deviceName"
        >
          <el-table-column
            :label="val.value"
            v-for="val in item.configuration"
            :key="val"
          >
            <template #default="{ row }">
              {{ row[item.deviceId][val.name] }}
            </template>
          </el-table-column>
        </el-table-column>
      </template>

      <el-table-column
        fixed="right"
        width="120"
        :label="$t('defalult.cz')"
        align="center"
      >
        <template #default="{ row }">
          <el-button type="text" @click="handleClick(row)">
            {{ $t('defalult.bj') }}
          </el-button>
          <el-button type="text" @click="handleDelete(row)">
            {{ $t('defalult.sc') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :background="background"
      :current-page="queryForm.page"
      :layout="layout"
      :page-size="queryForm.size"
      :total="total"
      style="text-align: right"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    ></el-pagination>
    <el-dialog
      v-model="dialogFormVisible"
      :title="title"
      width="90%"
      @close="close"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-divider content-position="left">基础项</el-divider>
            <el-form-item :label="$t('defalult.rq')" prop="date">
              <el-date-picker
                v-model="form['basic']['date']"
                type="date"
                :placeholder="$t('defalult.xzrq')"
              ></el-date-picker>
            </el-form-item>

            <el-row>
              <el-col style="display: flex">
                <el-form-item class="" label="进水COD" prop="inCod">
                  <el-input
                    v-model.trim="form['basic']['inCod']"
                    autocomplete="off"
                    class="inputWith"
                  ></el-input>
                </el-form-item>
                <el-form-item label="进水氨氮" prop="inAn">
                  <el-input
                    v-model.trim="form['basic']['inAn']"
                    autocomplete="off"
                    class="inputWith"
                  ></el-input>
                </el-form-item>
                <el-form-item label="进水TN" prop="inTn">
                  <el-input
                    v-model.trim="form['basic']['inTn']"
                    autocomplete="off"
                    class="inputWith"
                  ></el-input>
                </el-form-item>
                <el-form-item label="进水TP" prop="inTp">
                  <el-input
                    v-model.trim="form['basic']['inTp']"
                    autocomplete="off"
                    class="inputWith"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-row v-for="item in deviceList">
            <el-divider content-position="left">
              {{ item.deviceName }}
            </el-divider>
            <el-form-item :label="val.value" v-for="val in item.configuration">
              <el-input
                autocomplete="off"
                v-model.trim="form[item.deviceId][val.name]"
                class="inputWith"
              ></el-input>
            </el-form-item>
          </el-row>
        </el-row>
      </el-form>
      <div class="dialog-footer">
        <el-button type="primary" size="small" @click="save">保 存</el-button>
        <el-button size="small" @click="close">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  haianList,
  saveHian,
  addHian,
  delHian,
  HianDevice,
} from '@/api/analysis';
export default {
  name: 'Manage',
  components: {},
  data() {
    return {
      roleData: [],
      checkList: [],
      deviceList: [],
      tableData: [],
      rules: [],
      dialogFormVisible: false,

      form: {},
      date: [],
      title: '',
      lazy: true,
      activeName: 'first',
      layout: 'total, sizes, prev, pager, next, jumper',
      total: 0,
      background: true,
      listLoading: false,
      elementLoadingText: '正在加载...',
      queryForm: {
        page: 1,
        size: 20,
        date: '',
      },
    };
  },
  mounted() {
    this.initData();
  },

  computed: {
    height() {
      return 500;
    },
    getLabel(val) {
      return 'fasdfd';
    },
  },
  methods: {
    handleSizeChange(val) {
      this.queryForm.size = val;
      this.init();
    },
    handleCurrentChange(val) {
      this.queryForm.page = val;
      this.init();
    },
    //将时间格式化
    formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
      const year = date.getFullYear();
      const month = ('0' + (date.getMonth() + 1)).slice(-2);
      const day = ('0' + date.getDate()).slice(-2);
      const hours = ('0' + date.getHours()).slice(-2);
      const minutes = ('0' + date.getMinutes()).slice(-2);
      const seconds = ('0' + date.getSeconds()).slice(-2);
      return format
        .replace('YYYY', year)
        .replace('MM', month)
        .replace('DD', day)
        .replace('HH', hours)
        .replace('mm', minutes)
        .replace('ss', seconds);
    },

    standardToTime(val) {
      if (val) {
        this.queryForm.startTime = this.formatDate(val[0], 'YYYY-MM-DD');
        this.queryForm.endTime = this.formatDate(val[1], 'YYYY-MM-DD');
      } else {
        this.queryForm.startTime = null;
        this.queryForm.endTime = null;
      }
      this.init();
    },
    init() {
      haianList(this.queryForm).then(res => {
        console.log(res.data);
        this.tableData = res.data.items;
        this.total = res.data.total;
      });
    },

    initData() {
      HianDevice().then(res => {
        this.deviceList = res.data;
        this.checkList = this.deviceList.map(item => item.deviceId);
        this.init();
      });
      const configuration = [
        { name: 'treatmentWater', value: '处理水量' },
        { name: 'aerationTime', value: '曝气时间' },
        { name: 'elec', value: '电量' },
        { name: 'outCod', value: '出水COD' },
        { name: 'outAn', value: '出水氨氮' },
        { name: 'outTn', value: '出水TN' },
        { name: 'outTp', value: '出水TP' },
      ];

      // this.deviceList = [
      //   {
      //     deviceId: '3934',
      //     deviceName: '一体化AAO',
      //     configuration: [...configuration],
      //   },
      //   {
      //     deviceId: '3935',
      //     deviceName: 'SMC净化槽',
      //     configuration: [...configuration],
      //   },
      //   {
      //     deviceId: '3936',
      //     deviceName: '简化版净化槽',
      //     configuration: [...configuration],
      //   },
      //   {
      //     deviceId: '3937',
      //     deviceName: '1号户用机',
      //     configuration: [...configuration],
      //   },
      //   {
      //     deviceId: '3938',
      //     deviceName: '2号户用机',
      //     configuration: [...configuration],
      //   },
      //   {
      //     deviceId: '3939',
      //     deviceName: '3号户用机',
      //     configuration: [...configuration],
      //   },
      //   {
      //     deviceId: '3940',
      //     deviceName: '4号户用机',
      //     configuration: [...configuration],
      //   },
      //   {
      //     deviceId: '3941',
      //     deviceName: '集热测试户用机',
      //     configuration: [
      //       ...configuration,
      //       ...[
      //         { name: 'weatherTemp', value: '外界气温' },
      //         { name: 'waterTempUp', value: '最高水温' },
      //         { name: 'waterTempLow', value: '最低水温' },
      //       ],
      //     ],
      //   },
      // ];
      // console.log(JSON.stringify(this.deviceList));
    },
    add() {
      this.reSetForm();
      this.title = '新增';
      this.dialogFormVisible = true;
    },

    reSetForm() {
      let that = this;
      this.form = {
        basic: {
          date: null,
          inCod: null,
          inAn: null,
          inTn: null,
          inTp: null,
        },
      };
      this.deviceList.forEach(item => {
        this.form[item.deviceId] = {};
        item.configuration.forEach(val => {
          this.form[item.deviceId][val.name] = null;
        });
      });
      console.log(this.form);
    },
    save() {
      console.log(this.form);

      if (
        !(
          this.form.basic.date != null &&
          this.form.basic.inCod != null &&
          this.form.basic.inAn != null &&
          this.form.basic.inTn != null &&
          this.form.basic.inTp != null
        )
      ) {
        this.$message.error('基础数据必填');
        return;
      }

      if (this.form.basic?.id) {
        saveHian(this.form).then(res => {
          this.init();
          this.$message.success('保存成功');
          this.dialogFormVisible = false;
        });
      } else {
        addHian(this.form).then(res => {
          this.init();
          this.$message.success('新增成功');
          this.dialogFormVisible = false;
        });
      }
    },
    handleDelete(row) {
      // let that = this
      if (row.basic.id) {
        this.$confirm('你确定要删除当前项吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            delHian(row.basic.id).then(res => {
              this.init();
              this.$message({
                type: 'success',
                message: '删除成功',
              });
            });
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除',
            });
          });
      }
    },
    handleClick(val) {
      this.reSetForm();
      this.title = '修改';
      this.form = JSON.parse(JSON.stringify(val));
      this.dialogFormVisible = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.manage-container {
  width: 100%;

  .vab-query-form {
    margin-bottom: 30px;

    .el-input {
      width: 180px;
      margin-right: 20px;
    }
  }
}
.inputWith {
  width: 80px;
}
.manage-wrap {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .el-input {
    width: 200px !important;
  }
  .el-select {
    width: 200px !important;
  }
  .manage-button {
    padding-left: 12px;
  }
}
</style>

<style lang="scss">
.el-submenu__title:hover {
  background-color: rgba(#1890ff, 0.085) !important;
  color: hsla(208, 100%, 55%, 0.95) !important;
}
</style>
