<template>
  <!-- SaaS配置页面 -->
  <div class="testdiv">
    <div class="divborder newSearchDiv" style="margin: 0px">
      <!-- 搜索条件--客户名称 -->
      <div class="filter">
        <label>客户名称：</label>
        <Input class="searchInput" v-model="customName" />
      </div>
      <!-- 搜索条件--签约时间 -->
      <div class="filter">
        <label>签约时间：</label>
        <DatePicker
          class="searchInput middleWidth"
          type="daterange"
          :value="signTime"
          @on-change="signTimeChange"
        ></DatePicker>
      </div>
      <!-- 按钮组 -->
      <div class="searchBtn">
        <!-- 查询 -->
        <Button
          type="primary"
          class="twoWord"
          icon="ios-search"
          @click="Search()"
        >
          <span>查询</span>
        </Button>
        <!-- 添加 -->
        <Button
          type="success"
          class="twoWord"
          icon="md-add-circle"
          @click="add()"
        >
          <span>添加</span>
        </Button>
        <!-- 修改 -->
        <Button
          type="warning"
          class="twoWord"
          icon="ios-create-outline"
          @click="edit()"
        >
          <span>修改</span>
        </Button>
        <!-- 删除 -->
        <Button
          type="error"
          class="twoWord intervalRight"
          icon="md-close-circle"
          @click="del()"
        >
          <span>删除</span>
        </Button>
        <!-- 下载模板 -->
        <!-- <Button
          type="primary"
          class="fourWord"
          icon="md-download"
          @click="download()"
          >{{ $t(1005) }}</Button
        > -->
        <!-- Excel导入 -->
        <!-- <Upload
          style="display: inline-block"
          ref="upload"
          :action="action"
          name="excel-file"
          :headers="headers"
          :show-upload-list="false"
          :on-format-error="handleFormatError"
          :on-success="handleSuccess"
          :on-error="handleError"
          :format="['xlsx']"
        >
          <Button type="primary" class="fourWord" icon="md-cloud-upload">
            <span>导入Excel</span>
          </Button>
        </Upload> -->
      </div>
    </div>
    <div class="divborder newTableDiv">
      <Table
        class="tableClass"
        @on-current-change="handleRowChange"
        highlight-row
        :data="tableData"
        :columns="tableColumns"
      ></Table>
      <div class="pageDiv">
        <div class="pageDirection">
          <Page
            show-elevator
            show-sizer
            show-total
            :total="total"
            :current.sync="page"
            :page-size="pagesize"
            :page-size-opts="[10, 20, 30, 40, 100]"
            @on-change="handlePageChange"
            @on-page-size-change="handlePageSizeChange"
          ></Page>
        </div>
      </div>
    </div>
    <!-- 添加弹框 -->
    <Modal
      class="newModalClass"
      v-model="addModal"
      :styles="addModalStyles"
      :closable="false"
      :mask-closable="false"
    >
      <div slot="header">
        <span>添加签约记录</span>
      </div>
      <div class="modal_body">
        <div class="filter">
          <label>
            <i>*</i>
            客户名称：
          </label>
          <Input class="searchInput" v-model="addObj.customName" />
        </div>
        <div class="filter">
          <label>
            <i>*</i>
            设备数量：
          </label>
          <InputNumber
            class="searchInput"
            v-model="addObj.deviceNum"
            onkeypress="return /[\d]/.test(String.fromCharCode(event.keyCode))"
            :min="1"
          ></InputNumber>
        </div>
        <div class="x_row">
          <div class="filter">
            <label>
              <i>*</i>
              用户数量：
            </label>
            <InputNumber
              class="searchInput"
              v-model="addObj.userNum"
              onkeypress="return /[\d]/.test(String.fromCharCode(event.keyCode))"
              :min="1"
            ></InputNumber>
          </div>
        </div>
        <div class="x_row">
          <div class="filter">
            <label>
              <i>*</i>
              用户地址：
            </label>
            <!-- 省 -->
            <Select
              class="searchSelect"
              v-model="addObj.province"
              clearable
              @on-change="provinceChange"
            >
              <Option
                v-for="(v, i) in provinceList"
                :value="v.name"
                :key="v.id"
              >
                {{ v.name }}
              </Option>
            </Select>
            <!-- 市 -->
            <Select
              class="searchSelect"
              v-model="addObj.city"
              clearable
              @on-change="cityChange"
              style="margin-left: 4px"
              ref="cityDom"
            >
              <Option v-for="(v, i) in cityList" :value="v.name" :key="v.id">
                {{ v.name }}
              </Option>
            </Select>
            <!-- 区 -->
            <Select
              class="searchSelect"
              v-model="addObj.county"
              clearable
              style="margin-left: 4px"
              ref="countyDom"
            >
              <Option v-for="(v, i) in countyList" :value="v.name" :key="v.id">
                {{ v.name }}
              </Option>
            </Select>
            <!-- 详细地址 -->
            <Input
              class="searchInput"
              v-model="addObj.address"
              style="margin-left: 4px"
            />
          </div>
        </div>
        <div class="x_row">
          <div class="filter">
            <label>
              <i>*</i>
              签约时间：
            </label>
            <DatePicker
              type="datetime"
              format="yyyy-MM-dd HH:mm"
              class="searchInput"
              :value="addObj.signTime"
              @on-change="addSignTimeChange"
            ></DatePicker>
          </div>
        </div>
      </div>
      <div slot="footer">
        <Button size="large" @click="addModal = false">取消</Button>
        <Button size="large" type="primary" @click="confirmAdd()">确认</Button>
      </div>
    </Modal>
    <!-- 修改弹框 -->
    <Modal
      class="newModalClass"
      v-model="editModal"
      :styles="editModalStyles"
      :closable="false"
      :mask-closable="false"
    >
      <div slot="header">
        <span>修改签约记录</span>
      </div>
      <div class="modal_body">
        <div class="filter">
          <label>
            <i>*</i>
            客户名称：
          </label>
          <Input class="searchInput" v-model="editObj.customName" />
        </div>
        <div class="filter">
          <label>
            <i>*</i>
            设备数量：
          </label>
          <InputNumber
            class="searchInput"
            v-model="editObj.deviceNum"
            onkeypress="return /[\d]/.test(String.fromCharCode(event.keyCode))"
            :min="1"
          ></InputNumber>
        </div>
        <div class="x_row">
          <div class="filter">
            <label>
              <i>*</i>
              用户数量：
            </label>
            <InputNumber
              class="searchInput"
              v-model="editObj.userNum"
              onkeypress="return /[\d]/.test(String.fromCharCode(event.keyCode))"
              :min="1"
            ></InputNumber>
          </div>
        </div>
        <div class="x_row">
          <div class="filter">
            <label>
              <i>*</i>
              用户地址：
            </label>
            <!-- 省 -->
            <Select
              class="searchSelect"
              v-model="editObj.province"
              clearable
              @on-change="provinceChange"
            >
              <Option
                v-for="(v, i) in provinceList"
                :value="v.name"
                :key="v.id"
              >
                {{ v.name }}
              </Option>
            </Select>
            <!-- 市 -->
            <Select
              class="searchSelect"
              v-model="editObj.city"
              clearable
              @on-change="cityChange"
              style="margin-left: 4px"
              ref="cityDom"
            >
              <Option v-for="(v, i) in cityList" :value="v.name" :key="v.id">
                {{ v.name }}
              </Option>
            </Select>
            <!-- 区 -->
            <Select
              class="searchSelect"
              v-model="editObj.county"
              clearable
              style="margin-left: 4px"
              ref="countyDom"
            >
              <Option v-for="(v, i) in countyList" :value="v.name" :key="v.id">
                {{ v.name }}
              </Option>
            </Select>
            <!-- 详细地址 -->
            <Input
              class="searchInput"
              v-model="editObj.address"
              style="margin-left: 4px"
            />
          </div>
        </div>
        <div class="x_row">
          <div class="filter">
            <label>
              <i>*</i>
              签约时间：
            </label>
            <DatePicker
              type="datetime"
              format="yyyy-MM-dd HH:mm"
              class="searchInput"
              :value="editObj.signTime"
              @on-change="editSignTimeChange"
            ></DatePicker>
          </div>
        </div>
      </div>
      <div slot="footer">
        <Button size="large" @click="cancelEdit()">取消</Button>
        <Button size="large" type="primary" @click="confirmEdit()">确认</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import moment from "moment";
import config from "@/config";

export default {
  data() {
    const _this = this;
    let { $t } = this;
    return {
      // 搜索条件--客户名称
      customName: "",
      // 搜索条件--签约时间
      signTime: [],
      // Excel导入上传文件接口
      action: _this.axios.publicPath + "/abc",
      // Excel导入上传文件请求头
      headers: {
        token: localStorage.getItem("token"),
        timestamp: localStorage.getItem("timestamp"),
        nonce: localStorage.getItem("nonce"),
        sign: localStorage.getItem("sign"),
      },
      // 当前选中的行
      row: {},
      // 表格数据
      tableData: [],
      // 表格列
      tableColumns: [
        {
          title: $t(1008),
          render: (h, params) => {
            return h(
              "span",
              params.index + (_this.page - 1) * _this.pagesize + 1
            );
          },
          width: 75,
        },
        {
          title: "客户名称",
          key: "customer_name",
          align: "center",
        },
        {
          title: "设备数量",
          key: "machine_quantity",
          align: "center",
        },
        {
          title: "用户数量",
          key: "quantity",
          align: "center",
        },
        {
          title: "用户地址",
          align: "center",
          render: (h, params) => {
            let row = params.row;
            let str = `${row.province}${row.city}${row.area}${row.address}`;
            return h("div", {
              domProps: { innerHTML: str },
            });
          },
        },
        {
          title: "签约时间",
          align: "center",
          render: (h, params) => {
            let row = params.row;
            let str = moment(new Date(row.signing_time)).format(
              "YYYY-MM-DD HH:mm"
            );
            return h("div", {
              domProps: {
                innerHTML: str,
              },
            });
          },
        },
      ],
      // 表格数据总量
      total: 0,
      // 页码
      page: 1,
      // 页距
      pagesize: 10,
      // 操作类型 1 添加 2 修改
      operateType: 0,
      // 添加弹框标志位
      addModal: false,
      // 添加弹框数据
      addObj: {
        customName: "",
        deviceNum: null,
        userNum: null,
        signTime: "",
        province: "",
        city: "",
        county: "",
        address: "",
      },
      // 省列表数据
      provinceList: [],
      // 市列表数据
      cityList: [],
      // 县/区列表数据
      countyList: [],
      // 修改弹框标志位
      editModal: false,
      // 修改弹框数据
      editObj: {
        customName: "",
        deviceNum: null,
        userNum: null,
        signTime: "",
        province: "",
        city: "",
        county: "",
        address: "",
      },
    };
  },
  computed: {
    addModalStyles() {
      return { width: "750px" };
    },
    editModalStyles() {
      return { width: "750px" };
    },
  },
  mounted() {
    const _this = this;
    // 初始化表格列
    _this.tableColumns = _this.$time.initTableTitle(_this.tableColumns);
    this.Search();
    this.getProvinceList();
  },
  methods: {
    // 监听搜索条件--签约时间
    signTimeChange(v) {
      this.signTime = [...v];
    },
    // 上传文件格式错误钩子
    // handleFormatError(file) {
    //   let { $t } = this;
    //   this.$Message.error(`${$t(950396)}${file.name}${$t(950397)}`);
    // },
    // 上传文件成功钩子
    // handleSuccess(res, file) {
    //   const _this = this;
    //   let { $t } = this;
    //   if (res.ret == 1) {
    //     _this.$Message.success($t(950398));
    //   } else {
    //     if (`${res.msg}`.indexOf(",") != -1) {
    //       inittip(res.msg);
    //     } else {
    //       _this.$Message.error($t(res.msg));
    //     }
    //   }
    // },
    // 上传文件失败钩子
    // handleError() {
    //   this.$Message.error(this.$t(2010006));
    // },
    // 监听选中表格行
    handleRowChange(v) {
      this.row = v;
    },
    // 监听页码变化
    handlePageChange(v) {
      this.page = v;
      this.tableSearch();
    },
    // 监听页距变化
    handlePageSizeChange(v) {
      this.pagesize = v;
      this.tableSearch();
    },
    // 查询
    Search() {
      this.page = 1;
      this.pagesize = 10;
      this.tableSearch();
      // 支持模糊查询
      // this.xmgcqkJsonsData: 用于搜索的总体数据
      // let _search = this.jobNo.toLowerCase();
      // let newListData = []; // 用于存放搜索出来数据的新数组
      // if (_search) {
      //   this.xmgcqkJsonsData.filter (item => {
      //     if (item.code.toLowerCase().indexOf(_search)!==1) {
      //       xmgcqkJsonsData.push(item);
      //     }
      //   })
      // }
      // this.xmgcqkJsonsData = newListData;
    },
    tableSearch() {
      const _this = this;
      let { $Message, $t, customName, signTime } = this;
      let data = {
        page: this.page,
        pagesize: this.pagesize,
        customer_name: customName,
        startTime: signTime[0] ? signTime[0] : "",
        endTime: signTime[1] ? signTime[1] : "",
      };
      _this.axios
        .request({
          url: "/Dashboard/SaaSMonitor/Select",
          data,
          method: "post",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            let data = result.data;
            _this.total = result.total;
            _this.tableData = [];
            if (data && Array.isArray(data) && data.length) {
              _this.tableData = data;
            }
          } else {
            $Message.error($t(result.msg));
          }
        });
    },
    // 添加
    add() {
      const _this = this;
      _this.addObj = {
        customName: "",
        deviceNum: null,
        userNum: null,
        signTime: "",
        province: "",
        city: "",
        county: "",
        address: "",
      };
      _this.operateType = 1;
      _this.addModal = true;
    },
    // 修改
    edit() {
      const _this = this;
      let { row, $Message, $t, provinceList } = this;
      if (JSON.stringify(row) == "{}") {
        $Message.error($t(888814));
        return false;
      }

      _this.operateType = 2;

      let curProvince = provinceList.find((v) => {
        if (row.province == v.name) {
          return v;
        }
      });
      let params = {
        type: 2,
        status: 1,
        province_code: curProvince.code,
      };

      _this.axios
        .request({
          url: "config/Location/GetLocation",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.cityList = result.data;

            let curCity = _this.cityList.find((v) => {
              if (v.name == row.city) {
                return v;
              }
            });

            let params = {
              type: 3,
              status: 1,
              city_code: curCity.code,
            };

            _this.axios
              .request({
                url: "config/Location/GetLocation",
                params,
                method: "get",
              })
              .then((res) => {
                let result = res.data;
                if (result.ret == 1) {
                  _this.countyList = result.data;

                  _this.$nextTick(() => {
                    _this.editObj = {
                      customName: row.customer_name,
                      deviceNum: row.machine_quantity,
                      userNum: row.quantity,
                      signTime: row.signing_time,
                      province: row.province,
                      city: row.city,
                      county: row.area,
                      address: row.address,
                    };
                  });

                  _this.editModal = true;
                } else {
                  _this.$Message.error(_this.$t(result.msg));
                }
              });
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 监听添加表单中签约时间变化
    addSignTimeChange(v) {
      this.addObj.signTime = moment(v).format("YYYY-MM-DD HH:mm");
    },
    // 监听修改表单中签约时间变化
    editSignTimeChange(v) {
      this.editObj.signTime = moment(v).format("YYYY-MM-DD HH:mm");
    },
    // 获取省份列表数据
    getProvinceList() {
      const _this = this;
      let params = {
        type: 1,
        status: 1,
      };
      _this.axios
        .request({
          url: "config/Location/GetLocation",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.provinceList = result.data;
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 监听省份变化
    provinceChange(v) {
      const _this = this;
      let { operateType, addObj, editObj, provinceList } = this;

      _this.cityList = [];
      _this.$refs.cityDom.clearSingleSelect();
      _this.$refs.countyDom.clearSingleSelect();

      let curProvince = provinceList.find((v) => {
        if (operateType == 1) {
          if (addObj.province == v.name) {
            return v;
          }
        } else if (operateType == 2) {
          if (editObj.province == v.name) {
            return v;
          }
        }
      });

      if (!curProvince) {
        return false;
      }

      let params = {
        type: 2,
        status: 1,
        province_code: curProvince.code,
      };

      _this.axios
        .request({
          url: "config/Location/GetLocation",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.cityList = result.data;
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 监听市变化
    cityChange(v) {
      const _this = this;
      let { operateType, addObj, editObj, cityList } = this;

      _this.countyList = [];
      _this.$refs.countyDom.clearSingleSelect();

      let curCity = cityList.find((v) => {
        if (operateType == 1) {
          if (v.name == addObj.city) {
            return v;
          }
        } else if (operateType == 2) {
          if (v.name == editObj.city) {
            return v;
          }
        }
      });

      if (!curCity) {
        return false;
      }

      let params = {
        type: 3,
        status: 1,
        city_code: curCity.code,
      };

      _this.axios
        .request({
          url: "config/Location/GetLocation",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.countyList = result.data;
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 确认添加
    confirmAdd() {
      const _this = this;
      let { addObj, $t, $Message, provinceList, cityList, countyList } = this;
      if (!addObj.customName) {
        $Message.error($t(888805));
        return false;
      }
      if (!addObj.deviceNum) {
        $Message.error($t(888806));
        return false;
      }
      if (!addObj.userNum) {
        $Message.error($t(888807));
        return false;
      }
      if (!addObj.province) {
        $Message.error($t(888808));
        return false;
      }
      if (!addObj.city) {
        $Message.error($t(888809));
        return false;
      }
      if (!addObj.county) {
        $Message.error($t(888810));
        return false;
      }
      if (!addObj.address) {
        $Message.error($t(888811));
        return false;
      }
      if (!addObj.signTime) {
        $Message.error($t(888812));
        return false;
      }

      let curProvince = provinceList.find((v) => {
        if (v.name == addObj.province) {
          return v;
        }
      });
      let curCity = cityList.find((v) => {
        if (v.name == addObj.city) {
          return v;
        }
      });
      let curCounty = countyList.find((v) => {
        if (v.name == addObj.county) {
          return v;
        }
      });

      let params = {
        output: "json",
        ak: config.ak,
        address: `${curProvince.name}${curCity.name}${curCounty.name}${addObj.address}`,
      };

      _this.$jsonp(config.geoApi, params).then((res) => {
        if (res.status == 0) {
          let result = res.result;
          let location = result.location;
          // 经度值
          let lng = location.lng;
          // 纬度值
          let lat = location.lat;
          let data = {
            customer_name: addObj.customName,
            machine_quantity: addObj.deviceNum,
            quantity: addObj.userNum,
            province: curProvince.name,
            city: curCity.name,
            area: curCounty.name,
            address: addObj.address,
            longitude: `${lng}`,
            latitude: `${lat}`,
            signing_time: addObj.signTime,
          };
          _this.axios
            .request({
              url: "/Dashboard/SaaSMonitor/Add",
              data,
              method: "post",
            })
            .then((res) => {
              let result = res.data;
              if (result.ret == 1) {
                $Message.success($t(result.msg));
                _this.addModal = false;
                _this.Search();
              } else {
                $Message.error($t(result.msg));
              }
            });
        } else {
          $Message.error($t(888813));
        }
      });
    },
    // 删除
    del() {
      const _this = this;
      let { row, $Message, $t, $Modal } = this;
      if (JSON.stringify(row) == "{}") {
        $Message.error($t(888814));
        return false;
      }
      $Modal.confirm({
        title: $t(1018),
        content: "",
        width: "290px",
        closable: true,
        okText: $t(1004),
        onOk: () => {
          let params = {
            id: row.id,
          };
          _this.axios
            .request({
              url: "/Dashboard/SaaSMonitor/Delete",
              params,
              method: "get",
            })
            .then((res) => {
              let result = res.data;
              if (result.ret == 1) {
                $Message.success($t(result.msg));
                _this.Search();
              } else {
                $Message.error($t(result.msg));
              }
            });
        },
      });
    },
    // 下载模板事件
    download() {
      if (this.row.id == 0 || this.row.id == "" || this.row.id == undefined) {
        this.$Message.error(this.$t(1043));
        return false;
      }
      // this.request(
      //   '/config/MonthReportRecord/GetPdfFileName?id=' +
      //       this.row.id,
      //    '',
      //    'get'
      // )
      // .then(res => {
      //   if (res.data.ret == 1) {
      //     var url = '/config/MonthReportRecord/DownloadReport?id=' + this.row.id;
      //     var xhr = new XMLHttpRequest();
      //     xhr.open('GET', url, true);
      //     xhr.responseType = 'blob';
      //     xhr.onload = function() {
      //       if (this.status === 200) {
      //         var blob = this.response; // 获取返回值
      //         var a = document.createElement('a');
      //         a.download = res.data;
      //         a.href = window.URL.createObjectURL(blob);
      //         a.click();
      //       }else {
      //         this.$Message.error(this.$t(1097) + '!');
      //         return false;
      //       }
      //     };
      //     xhr.send();
      //   }else {
      //     this.$Message.error(this.$t(res.msg));
      //   }
      // })
    },
    // 取消修改
    cancelEdit() {
      this.editModal = false;
      this.cityList = [];
      this.countyList = [];
    },
    // 确认修改
    confirmEdit() {
      const _this = this;
      let {
        editObj,
        $t,
        $Message,
        provinceList,
        cityList,
        countyList,
        row,
      } = this;
      if (!editObj.customName) {
        $Message.error($t(888805));
        return false;
      }
      if (!editObj.deviceNum) {
        $Message.error($t(888806));
        return false;
      }
      if (!editObj.userNum) {
        $Message.error($t(888807));
        return false;
      }
      if (!editObj.province) {
        $Message.error($t(888808));
        return false;
      }
      if (!editObj.city) {
        $Message.error($t(888809));
        return false;
      }
      if (!editObj.county) {
        $Message.error($t(888810));
        return false;
      }
      if (!editObj.address) {
        $Message.error($t(888811));
        return false;
      }
      if (!editObj.signTime) {
        $Message.error($t(888812));
        return false;
      }

      let curProvince = provinceList.find((v) => {
        if (v.name == editObj.province) {
          return v;
        }
      });
      let curCity = cityList.find((v) => {
        if (v.name == editObj.city) {
          return v;
        }
      });
      let curCounty = countyList.find((v) => {
        if (v.name == editObj.county) {
          return v;
        }
      });

      let params = {
        output: "json",
        ak: config.ak,
        address: `${curProvince.name}${curCity.name}${curCounty.name}${editObj.address}`,
      };

      _this.$jsonp(config.geoApi, params).then((res) => {
        if (res.status == 0) {
          let result = res.result;
          let location = result.location;
          // 经度值
          let lng = location.lng;
          // 纬度值
          let lat = location.lat;
          let data = {
            id: row.id,
            customer_name: editObj.customName, // 客户名称
            machine_quantity: editObj.deviceNum, // 设备数量
            quantity: editObj.userNum, // 用户数量
            province: curProvince.name,
            city: curCity.name,
            area: curCounty.name,
            address: editObj.address,
            longitude: `${lng}`,
            latitude: `${lat}`,
            signing_time: editObj.signTime,
          };
          _this.axios
            .request({
              url: "/Dashboard/SaaSMonitor/Update",
              data,
              method: "post",
            })
            .then((res) => {
              let result = res.data;
              if (result.ret == 1) {
                $Message.success($t(result.msg));
                _this.editModal = false;
                _this.tableSearch();
              } else {
                $Message.error($t(result.msg));
              }
            });
        } else {
          $Message.error($t(888813));
        }
      });
    },
  },
};
</script>