<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!-- <div>
        <el-input
          v-model="searchParam.mineName"
          clearable
          size="small"
          placeholder="所属矿山"
          style="width: 400px"
          class="filter-item"
        />
        <el-button
          class="filter-item"
          size="mini"
          type="success"
          icon="el-icon-search"
          @click="searchSubmit"
          >搜索</el-button
        >
        <el-button
          class="filter-item"
          size="mini"
          type="warning"
          icon="el-icon-refresh-left"
          @click="searchParamReset"
          >重置</el-button
        >
      </div> -->
      <el-button
        class="filter-item"
        size="mini"
        type="primary"
        icon="el-icon-plus"
        @click="doAdd()"
        >新增</el-button
      >
    </div>
    <!--弹出框1-->
    <el-dialog
      append-to-body
      :close-on-click-modal="true"
      :visible.sync="dialog1Show"
      title="监控配置"
      width="960px"
    >
      <el-form
        ref="dialog1Form"
        :hide-required-asterisk="!dialog1Editing"
        :model="dialog1Data"
        :rules="dialog1Rules"
        size="mini"
        label-width="180px"
        style="margin-right: 80px"
      >
        <el-row :gutter="20">
          
            <el-col :span="24">
              <el-form-item label="所属企业：" prop="enterpriseId">
              <el-select
                v-model="dialog1Data.enterpriseId"
                placeholder="请选择"
                @change="enterpriseChange"
                style="width: 400px"
                :disabled="editState == 3"
              >
                <el-option
                  v-for="item in options4enterpriseIdList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属矿山：" prop="mineId">
              <el-select
                v-model="dialog1Data.mineId"
                placeholder="请选择"
                clearable
                size="small"
                class="filter-item"
                style="width: 400px"
                :disabled="editState == 3"
              >
                <el-option
                  v-for="(mine, key) in mineList"
                  :key="key"
                  :label="mine.name"
                  :value="mine.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="appKey：" prop="appKey">
              <el-input
                v-model="dialog1Data.appKey"
                :disabled="editState == 3"
                maxlength="100"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="appSecret:" prop="appSecret">
              <el-input
                v-model="dialog1Data.appSecret"
                :disabled="editState == 3"
                maxlength="100"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="margin: 10px 0">
      
        <!-- <el-divider></el-divider>
        <h5>监控摄像头</h5> -->
        <el-divider content-position="left">通道列表</el-divider>
        
        <div
          style="margin: 10px 0; padding-left: 30px"
          v-for="(employee, eIndex) in dialog1Data.videoChannelList"
          :key="eIndex"
        >
          <el-input
            v-model="employee.channel"
            placeholder="通道(如:1.hd.live)"
            type="text"
            style="width: 150px"
            :disabled="editState == 3"
          />
          <el-input
            v-model="employee.id"
            placeholder="萤石云ID(G67791073)"
            type="text"
            style="width: 150px"
            :disabled="editState == 3"
          />
          <el-input
            v-model="employee.name"
            placeholder="名称"
            type="text"
            style="width: 150px"
            :disabled="editState == 3"
          />
          <el-input
            v-model="employee.captcha"
            placeholder="验证码"
            type="text"
            style="width: 150px"
            :disabled="editState == 3"
          />
          <el-input
            v-model="employee.remark"
            placeholder="备注"
            type="text"
            style="width: 150px"
            :disabled="editState == 3"
          />
          <el-button
            type="danger"
            @click="deleteEmployee(index, eIndex)"
            :disabled="editState == 3"
            >删除</el-button
          >
        </div>
        <div
          style="margin: 10px 0; padding-left: 30px"
        >
          <el-input
            v-model="employeeAddObj.channel"
            placeholder="通道(如:1.hd.live)"
            type="text"
            style="width: 150px"
            :disabled="editState == 3"
          />
          <el-input
            v-model="employeeAddObj.id"
            placeholder="萤石云ID(G67791073)"
            type="text"
            style="width: 150px"
            :disabled="editState == 3"
          />
          <el-input
            v-model="employeeAddObj.name"
            placeholder="名称"
            type="text"
            style="width: 150px"
            :disabled="editState == 3"
          />
          <el-input
            v-model="employeeAddObj.captcha"
            placeholder="验证码"
            type="text"
            style="width: 150px"
            :disabled="editState == 3"
          />
          <el-input
            v-model="employeeAddObj.remark"
            placeholder="备注"
            type="text"
            style="width: 150px"
            :disabled="editState == 3"
          />
          <el-button
          type="primary"
          @click="addEmployee"
          :disabled="editState == 3"
          >添加</el-button
        >
        </div>
      </div>
      <div v-show="dialog1Editing" slot="footer" class="dialog-footer">
        <el-button type="text" @click="dialog1Show = false">取消</el-button>
        <el-button
          :loading="dialog1Saving"
          type="primary"
          @click="dialog1Submit"
          >确认</el-button
        >
      </div>
    </el-dialog>

    <!--表格-->
    <el-table ref="table" v-loading="searching" :data="tableData" row-key="id">
      <el-table-column
        :show-overflow-tooltip="true"
        prop="enterpriseName"
        label="所属企业"
        align="center"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="mineName"
        label="所属矿山"
        align="center"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="id"
        label="ID"
        width="100px"
        align="center"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="appKey"
        label="APPKEY"
        align="center"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="appSecret"
        label="APPSECRET"
        align="center"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="channelNumber"
        label="通道数量"
        align="center"
      />
      
      <el-table-column label="操作" width="300px" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" round @click="doEdit(scope.row, false)"
            >查看</el-button
          >
          <el-button size="mini" round @click="doEdit(scope.row, true)"
            >修改</el-button
          >
          <el-button size="mini" round @click="doDelete(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :page-sizes="[10, 20, 50, 100]"
      :current-page.sync="searchParam.page"
      :page-size.sync="searchParam.size"
      :total="searchResult.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>
  
  <script>
import videoConfigApi from "@/api/kd/videoConfig";
import { getToken } from "@/utils/auth";
import {getCompanyList} from '@/api/system/user'

const searchParam = {
  // 默认搜索条件
  page: 1,
  size: 10,
  mineName: "",
};
export default {
  name: "videoConfig", // 本页面名
  data() {
    return {
      options4enterpriseIdList: [],
      mineList: [],
      selectedMine: {},
      httpHeaders: {
        Authorization: getToken(),
      },
      videoConfigApi: videoConfigApi,
      searching: false,
      exporting: false,
      searchParam: {},
      searchResult: {
        total: 0,
        results: [], // 搜索结果
      },
      dialog1Show: false,
      dialog1Editing: false,
      dialog1Saving: false,
      dialog1Data: {
        mineId:'',
        appKey:'',
        appSecret: '',
        videoChannelList: [
          {
            channel: "",
            id: "",
            name: "",
            remark: "",
            captcha: ''
          },
        ],
      },
      dialog1Rules: {
        enterpriseId: [{ required: true, message: '请选择' }],
        appKey: [{ required: true, message: "请填写" }],
        mineId: [{ required: true, message: "请选择" }],
        appSecret: [{ required: true, message: "请填写" }],
      },
      editState: 0, // （刚打开窗口时）记录了上次窗口作用；（保存编辑时）记录了当前窗口作用； 0无 1新增 2修改 3查看
      employeeAddObj:{
        channel: "",
        id: "",
        name: "",
        remark: "",
        captcha: ''
      },
      addingData: {
        videoChannelList: [],
      }, // 上次正在新增时的内容，下次打开dialog1窗口时记录下来
    };
  },
  computed: {
    tableData() {
      // 此处对返回值进行算法重组
      return this.searchResult.results;
    },
  },
  mounted() {
    this.searchParamReset();
    this.searchSubmit();
     // 获取企业公司
     getCompanyList({})
      .then((res) => {
        this.options4enterpriseIdList = res.body;
      });
  },
  methods: {
    // 当前页的条数变化
    handleSizeChange(val) {
      this.searchParam.size = val;
      this.searchSubmit();
    },
    // 当前第几页
    handleCurrentChange(val) {
      this.searchParam.page = val;
      this.searchSubmit();
    },
    getMineTypeByMineId(mineId){
        return this.mineList.find((item)=>{
          return item.id === mineId
        })
    },
    validData(data){
      return data.filter((item) => {
        return !item.channel || !item.id || !item.name
      }).length
    },
    enterpriseChange(value){
      // this.addingData.mineId = ''
      // 矿山选项卡
      this.getAllMineByEnterpriseId(value)
    },
    getAllMineByEnterpriseId(enterpriseId){
      videoConfigApi.getAllMineByEnterpriseId({
        enterpriseId
      }).then(response => {
        this.mineList = response.body
        // this.mineList = response.body.map((item)=>{
        //   item.id = item.id+''
        //   return item
        // })
        // this.dialog1Data.mineId = ''
      })
    },
    addEmployee() {
      // 添加组成员
      this.dialog1Data.videoChannelList.push({...this.employeeAddObj});
      this.employeeAddObj = {
        channel: "",
        id: "",
        name: "",
        remark: "",
        captcha: ''
      }
    },
    deleteEmployee(index, eIndex) {
      this.dialog1Data.videoChannelList.splice(
        eIndex,
        1
      );
    },

    searchParamReset() {
      this.searchParam = JSON.parse(JSON.stringify(searchParam));
    },
    searchSubmit() {
      this.searching = true;
      videoConfigApi
        .getDataList(this.searchParam)
        .then((response) => {
          console.log()
          this.searching = false;
          this.searchResult.results = response.body.results;
          this.searchResult.total = response.body.total;

        })
        .catch(() => {
          this.searching = false;
        });
    },
    dialog1Submit() {
      this.$refs["dialog1Form"].validate((valid) => {
        if (valid) {
          if(!this.mineList.length){
            this.$message.warning('所属矿山与所属企业不匹配，请重新选择')
            return
          }
          if(!this.dialog1Data.videoChannelList.length){
            this.$message.warning('通道数据至少一条，请确认')
            return
          }
          if(!!this.validData(this.dialog1Data.videoChannelList)){
            this.$message.warning('通道数据存在空项，请确认')
            return
          }
          
          this.dialog1Saving = true;
          const mineInfo = this.getMineTypeByMineId(this.dialog1Data.mineId)
          this.dialog1Data.mineType = mineInfo.type
          this.dialog1Data.mineName = mineInfo.name
          if(mineInfo.enterpriseId !== this.dialog1Data.enterpriseId){
            this.$message.warning('所属矿山与所属企业不匹配，请重新选择')
            return
          }
          // this.dialog1Data.mineId = "1"; // 地下矿山
          if (this.editState === 1) {
            videoConfigApi
              .add(this.dialog1Data)
              .then(() => {
                this.dialog1Show = false;
                this.$message.success("保存成功");
                setTimeout(() => {
                  // 立即清除会导致输入框Validate一闪变红
                  this.dialog1Data = {};
                  this.dialog1Saving = false;
                }, 500);
                this.searchSubmit();
              })
              .catch(() => {
                this.dialog1Saving = false;
              });
          } else if (this.editState === 2) {
            // 修改
            videoConfigApi
              .set(this.dialog1Data)
              .then(() => {
                this.dialog1Show = false;
                this.$message.success("修改成功");
                setTimeout(() => {
                  // 立即清除会导致输入框Validate一闪变红
                  this.dialog1Data = {};
                  this.dialog1Saving = false;
                }, 500);
                this.searchSubmit();
              })
              .catch(() => {
                this.dialog1Saving = false;
              });
          } else {
            this.$message.error("出错啦，请重试");
            this.dialog1Saving = false;
          }
        }
      });
    },
    beforeDialog1Open() {
      // // 窗口打开前的统一操作
      // if (this.editState === 1) {
      //   this.addingData = this.dialog1Data;
      // }
    },
    doAdd() {
      this.beforeDialog1Open();
      this.editState = 1;
      this.dialog1Editing = true;
      // this.dialog1Data = this.addingData; // 初始值：上次编辑的内容
      this.dialog1Data = {
        mineId:'',
        appKey:'',
        appSecret: '',
        videoChannelList: [],
      }
      this.dialog1Show = true;
      this.$nextTick(() => {
        this.$refs["dialog1Form"].clearValidate();
      });
    },
    doEdit(row, isEdit) {
      this.beforeDialog1Open();
      this.editState = isEdit ? 2 : 3;
      this.dialog1Data = row;
      this.dialog1Data.mineId = row.mineId
      this.dialog1Editing = isEdit;
      this.dialog1Show = true;
      this.$refs["dialog1Form"].clearValidate();
      // videoConfigApi
      //   .getById(id)
      //   .then((response) => {
      //     this.dialog1Data = response;
      //     this.dialog1Editing = isEdit;
      //     this.dialog1Show = true;
      //     this.$nextTick(() => {
      //       this.$refs["dialog1Form"].clearValidate();
      //       this.getAllMineByEnterpriseId(this.dialog1Data.enterpriseId);
      //     });
      //   })
      //   .catch(() => {
      //     this.searchSubmit();
      //   });
    },
    doDelete(id) {
      this.$confirm("确定要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(
        () => {
          videoConfigApi.deleteById([id]).then((response) => {
            this.$message({
            type: "success",
            message: "操作成功",
          });
            this.searchSubmit();
          });
        },
        () => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        }
      );
    },
  },
};
</script>
  
  <style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
::v-deep .vue-treeselect__control,
::v-deep .vue-treeselect__placeholder,
::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
  