<template>
  <el-dialog
    class="addPhotoDialog"
    :title="photoDialogTitle"
    :visible.sync="isShow"
    :close-on-click-modal="false"
    width="800px"
  >
    <el-form
      label-position="left"
      label-width="74px"
      ref="formgrapInfo"
      :rules="rules"
      :model="formInfo"
    >
      <el-form-item label="线路名称：" prop="lineId">
        <el-select
          v-model="formInfo.lineId"
          placeholder="请选择"
          @change="getTowerchange"
        >
          <el-option
            v-for="item in lineOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="杆塔名称：" prop="towerId">
        <el-select v-model="formInfo.towerId" placeholder="请选择" filterable>
          <el-option
            v-for="item in toweridOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="装置ID：" prop="cmdid">
        <el-input v-model="formInfo.cmdid" autocomplete="on"></el-input>
      </el-form-item>
      <el-form-item label="装置类型：" prop="devType">
        <el-select v-model="formInfo.devType" placeholder="请选择">
          <el-option
            v-for="item in devTypeOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="云台选择：" prop="hasPan">
        <el-select v-model="formInfo.hasPan" placeholder="请选择">
          <el-option
            v-for="item in hasPanOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="装置名称：" prop="equipName">
        <el-input v-model="formInfo.equipName" auto-complete="on"></el-input>
      </el-form-item>
      <el-form-item label="SIM卡：" prop="sim">
        <el-input v-model="formInfo.sim" auto-complete="on"></el-input>
      </el-form-item>
      <el-form-item label="网络类型：" prop="netType">
        <el-select v-model="formInfo.netType" placeholder="请选择">
          <el-option
            v-for="item in networkOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="装置型号：" prop="model">
        <el-input v-model="formInfo.model" auto-complete="on"></el-input>
      </el-form-item>
      <el-form-item label="装置厂家：" prop="bsManufacturer">
        <el-input
          v-model="formInfo.bsManufacturer"
          auto-complete="on"
        ></el-input>
      </el-form-item>
      <el-form-item label="规约版本：" prop="protocolVersion">
        <!-- <el-input
          v-model="formInfo.protocolVersion"
          auto-complete="on"
        ></el-input> -->
        <el-select v-model="formInfo.protocol" placeholder="请选择">
          <el-option
            v-for="item in protocolOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="投运日期：" prop="workingDate">
        <el-date-picker
          class="dateClass"
          v-model="formInfo.workingDate"
          type="date"
          placeholder="选择日期"
          format="yyyy 年 MM 月 dd 日"
          value-format="timestamp"
        ></el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="状态：" prop="status">
        <el-select v-model="formInfo.statusId" placeholder="请选择">
          <el-option v-for="item in statusOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item> -->
      <el-divider></el-divider>
      <h4>添加通道</h4>
      <div class="addchannel" ref="channelBoxref">
        <div
          class="channelBoxadd"
          v-for="(val, index) in formInfo.list"
          :key="index"
        >
          <el-form-item label="通道号：">
            <el-select
              v-model="val.id"
              placeholder="请选择通道号"
              @change="changeHandle"
            >
              <el-option
                v-for="item in filterOption"
                :key="item.id"
                :label="item.channelname"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="通道昵称：">
            <el-input
              v-model="val.alias"
              placeholder="请输入通道昵称"
            ></el-input>
          </el-form-item>
          <div class="btngrop">
            <el-button
              v-if="index !== 0"
              type="danger"
              icon="el-icon-minus"
              @click="deleteModule(val, index)"
            ></el-button>
            <el-button
              icon="el-icon-plus"
              type="primary"
              @click="addModule()"
              v-if="index + 1 == formInfo.list.length"
            ></el-button>
          </div>
        </div>
        <!-- <el-form-item label="通道(可多选)：" prop="id">
          <el-checkbox-group
            class="channelBox"
            v-model="formInfo.id"
            v-if="channelOptions.length > 0"
          >
            <el-checkbox
              border
              v-for="item in channelOptions"
              :key="item.id"
              :label="item.id"
              :value="item.channelname"
              >{{ item.channelname }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item> -->
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="isShow = false">取 消</el-button>
      <el-button type="primary" @click="submitForm()">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {
  addTerminalJoggle,
  updateTerminalJoggle,
  getAllChannelListJoggle,
  getLineAndGtInfo,
  getProtocolList,
} from "@/utils/api/index";
export default {
  props: {
    photoDialog: {
      type: Boolean,
    },
    photoDialogTitle: {
      type: String,
      default: "新增",
    },
  },

  data() {
    let validCmid = (rule, value, callback) => {
      let reg = /^[0-9A-Za-z_/\\/-]{17}$/;
      if (!reg.test(value)) {
        callback(new Error("装置id为17位编码"));
      } else {
        callback();
      }
    };
    return {
      isShow: false,
      formInfo: {},
      channelOptions: [], //所有通道列表
      filterOption: [], //筛选后的通道列表
      lineOptions: [], //线路
      toweridOptions: [], //杆塔
      //装置类型
      devTypeOptions: [
        {
          id: 1,
          name: "微拍",
        },
        {
          id: 2,
          name: "覆冰拉力",
        },
        {
          id: 3,
          name: "微气象",
        },
      ],
      networkOptions: [
        {
          id: 1,
          name: "移动",
        },
        {
          id: 2,
          name: "联通",
        },
        {
          id: 3,
          name: "电信",
        },
      ], //网络类型
      statusOptions: [
        {
          id: 1,
          name: "在运",
        },
        {
          id: 2,
          name: "停运",
        },
        {
          id: 3,
          name: "调试",
        },
      ], //状态
      hasPanOptions: [
        {
          id: 0,
          name: "否",
        },
        {
          id: 1,
          name: "是",
        },
      ],
      protocolOptions: [], //规约版本
      rules: {
        cmdid: [
          { required: true, message: "请输入装置ID", trigger: "blur" },
          { validator: validCmid, trigger: "blur" },
        ],
      },
      photoDialogtype: 0, //1 线路change时，修改杆塔数据
    };
  },
  mounted() {
    this.getProtocol();
  },
  created() {},
  watch: {},
  methods: {
    getProtocol() {
      //获取规约版本
      getProtocolList()
        .then((res) => {
          console.log(res);
          this.protocolOptions = res.data.list;
          console.log(this.protocolOptions);
        })
        .catch((err) => {});
    },
    //判断
    getdataform(val) {
      this.getLine();
      this.getChannel();
      if (val == null) {
        return (this.formInfo = {
          lineId: "",
          towerId: "",
          cmdid: "",
          equipName: "",
          devType: this.devTypeOptions[0].id,
          hasPan: this.hasPanOptions[0].id,
          sim: "",
          netType: this.networkOptions[0].id,
          model: "",
          bsManufacturer: "",
          protocol: this.protocolOptions[0].id,
          workingDate: new Date().getTime(),
          list: [
            {
              id: "",
              alias: "",
            },
          ],
        });
      }
      if (val.list.length == 0) {
        console.log(val);
        console.log("我是没有通道的");
        val.list.push({
          id: "",
          alias: "",
        });
      }

      //this.formInfo = val;
      this.formInfo = JSON.parse(JSON.stringify(val));
      this.$set(
        this.formInfo,
        "workingDate",
        new Date(this.formInfo.workingDate).getTime()
      );
      console.log(this.formInfo.workingDate);
    },
    //通道号值改变
    changeHandle() {
      this.filterOption = this.channelOptions.filter(
        (val) => !this.formInfo.list.some((item) => item.id === val.id)
      );
    },
    //新增一行
    addModule() {
      //新增一行
      this.formInfo.list.push({
        id: "",
        alias: "",
      });
      this.filterOption = this.channelOptions.filter(
        (val) => !this.formInfo.list.some((item) => item.id === val.id)
      );
      this.$nextTick(() => {
        console.log(this.$refs.channelBoxref);
        if (this.$refs.channelBoxref) {
          console.log(this.$refs.channelBoxref.scrollHeight);
          this.$refs.channelBoxref.scrollTop =
            this.$refs.channelBoxref.scrollHeight;
        }
      });
    },
    //删除一行
    deleteModule(item, index) {
      console.log(item, index);
      const itemList = this.formInfo.list.indexOf(item);
      if (itemList !== -1) {
        this.formInfo.list.splice(index, 1);
      }
      this.filterOption = this.channelOptions.filter(
        (val) => !this.formInfo.list.some((item) => item.id === val.id)
      );
    },
    // 保存确定操作
    submitForm() {
      const newListLength = new Set(this.formInfo.list.map((item) => item.id))
        .size;
      const listLength = this.formInfo.list.length;
      if (listLength > newListLength) {
        return this.$message.error("通道不能重复");
      }
      this.$refs.formgrapInfo.validate((valid) => {
        if (valid) {
          if (this.photoDialogTitle == "新增") {
            // this.formInfo = {
            //   lineId: this.formInfo.lineId,
            //   towerId: this.formInfo.towerId,
            //   cmdId: this.formInfo.cmdId,
            //   equipName: this.formInfo.equipName,
            //   sim: this.formInfo.sim,
            //   list: this.formInfo.list,
            //   displayName: this.formInfo.cmdId,
            // };
            this.$set(this.formInfo, "workingDate", new Date().getTime());
            this.$set(this.formInfo, "displayName", this.formInfo.cmdid);
            console.log(this.formInfo);
            addTerminalJoggle(this.formInfo)
              .then((res) => {
                this.isShow = false;
                this.$message({
                  duration: 1500,
                  showClose: true,
                  message: "添加成功",
                  type: "success",
                });
                this.$parent.terminalList(); //刷新
              })
              .catch((err) => {
                this.$message({
                  duration: 1500,
                  showClose: true,
                  message: "添加失败",
                  type: "error",
                });
              });
          } else {
            console.log(this.formInfo);

            updateTerminalJoggle(this.formInfo)
              .then((res) => {
                this.isShow = false;
                this.$message.success("修改成功");
                this.$parent.terminalList();
              })
              .catch((err) => {
                this.$message.error("修改失败");
              });
          }
        } else {
          return false;
        }
      });
    },

    //获取所有线路
    getLine() {
      getLineAndGtInfo({ type: 1 }).then((res) => {
        this.lineOptions = res.data.list;
        if (res.data.list.length == 0) {
          this.lineOptions = [];
          this.formInfo.lineId = "";
        } else {
          this.lineOptions = res.data.list;
          if (this.photoDialogTitle == "新增") {
            // this.formInfo.lineId = res.data.list[0].id;
            this.$set(this.formInfo, "lineId", res.data.list[0].id);
          }
        }
        // this.dyOptions = res.data.list;
        // this.formdata.dyid = res.data.list == [] ? "" : res.data.list[0].id;
        this.getTower();
      });
    },
    //获取所有杆塔
    getTower() {
      getLineAndGtInfo({ type: 2, id: this.formInfo.lineId })
        .then((res) => {
          if (res.data.list.length == 0) {
            this.toweridOptions = [];
            this.formInfo.towerId = "";
          } else {
            this.toweridOptions = res.data.list;
            if (this.photoDialogTitle == "新增" || this.photoDialogtype == 1) {
              // this.formInfo.towerId = res.data.list[0].id;
              this.$set(this.formInfo, "towerId", res.data.list[0].id);
              this.photoDialogtype = 0;
            }
          }
        })
        .catch((err) => {});
    },
    getTowerchange() {
      if (this.photoDialogTitle == "修改") {
        this.photoDialogtype = 1;
      }
      this.getTower();
    },
    //获取所有通道
    getChannel() {
      getAllChannelListJoggle()
        .then((res) => {
          this.channelOptions = res.data.list;
          this.filterOption = res.data.list;
          if (this.photoDialogTitle == "新增") {
            this.formInfo.list[0].id = this.filterOption[0].id;
          }
          //this.formInfo.list[0].id = this.filterOption[0].id;
        })
        .catch((err) => {});
    },
    display() {
      this.isShow = true;
    },
    hide() {
      this.isShow = false;
    },
    // handleclose() {
    //   this.$parent.terminalList();
    // },
  },
};
</script>
<style lang="less">
.addPhotoDialog {
  .el-dialog {
    .el-form {
      display: flex;
      flex-wrap: wrap;
      .el-form-item {
        width: 364px;
        margin-right: 16px;
        .el-select {
          width: 100%;
        }
        .el-checkbox-group {
          .el-checkbox {
            margin-right: 12px;
          }
        }
        .el-form-item__label {
          padding-right: 0px;
        }
        .dateClass {
          width: 290px;
        }
      }
      .el-divider--horizontal {
        margin: 12px;
      }
      h4 {
        font-size: 16px;
        font-weight: normal;
        margin-bottom: 6px;
        line-height: 24px;
      }
      .addchannel {
        max-height: 200px;
        overflow: auto;
        .channelBoxadd {
          display: flex;
          //justify-content: space-between;
          padding-right: 6px;
          .el-form-item {
            width: 310px;
          }
          .btngrop {
            margin-bottom: 16px;
            margin-left: 16px;
            height: 32px;
            .el-button--small {
              padding: 9px 8px;
              width: 30px;
            }
          }
        }
      }
      .channelBox {
        .el-checkbox {
          margin-right: 12px;
          margin-left: 0px;
          margin-bottom: 8px;
        }
      }
    }
  }
}
</style>
