<!-- 主页模块 主页一览-->
<template>
  <div>
    <div class="head">
      <span class="headicon">基本信息</span>
    </div>
    <div class="top-buttons">
      <el-button type="primary"
                 size="small"
                 @click="save">保存</el-button>
      <el-button v-show="state"
                 size="small"
                 @click="backToAdd">保存并继续添加</el-button>
      <el-button size="small"
                 @click="back">返回列表</el-button>
    </div>
    <div class="form">
      <el-form ref="ruleForm"
               :model="ruleForm"
               label-position="right"
               label-width="120px"
               :rules="rules">
        <el-form-item label="公司中文名称"
                      prop="tenantName"
                      class="aaa">
          <el-input v-model="ruleForm.tenantName"
                    size="small"
                    @change="edited = true"
                    class="page-form-input"
                    maxlength="90" />
        </el-form-item>
        <el-form-item label="公司英文名称"
                      prop="tenantEnName"
                      class="aaa">
          <el-input v-model="ruleForm.tenantEnName"
                    size="small"
                    @change="edited = true"
                    class="page-form-input"
                    maxlength="90" />
        </el-form-item>
        <el-form-item label="公司简称">
          <el-input size="small"
                    v-model="ruleForm.compSimpleNameEn"
                    class="page-form-input"
                    disabled />
          <el-tooltip class="item"
                      effect="light"
                      content="用于标记采购单号规则标识"
                      placement="bottom-start">
            <svg-icon icon-class="talk"
                      class="talk" />
          </el-tooltip>
        </el-form-item>
        <el-form-item label="公司域名"
                      prop="compDomainName"
                      class="aaa">
          <el-input maxlength="40"
                    class="page-form-input"
                    @change="edited = true"
                    size="small"
                    v-model="ruleForm.compDomainName" />
        </el-form-item>
        <el-form-item label="联系人"
                      prop="linkmanName"
                      class="aaa">
          <el-input v-model="ruleForm.linkmanName"
                    size="small"
                    @change="edited = true"
                    class="page-form-input" />
        </el-form-item>
        <el-form-item label="联系电话"
                      prop="linkmanPhone">
          <el-input v-model="ruleForm.linkmanPhone"
                    @change="edited = true"
                    size="small"
                    class="page-form-input" />
        </el-form-item>
        <el-form-item label="联系人邮箱"
                      prop="linkmanEmail">
          <el-input v-model="ruleForm.linkmanEmail"
                    @change="edited = true"
                    size="small"
                    class="page-form-input" />
        </el-form-item>
        <el-form-item label="专属客服"
                      prop="customerServiceStaffId"
                      class="aaa">
          <el-select v-model="ruleForm.customerServiceStaffId"
                     placeholder="请选择"
                     @change="edited = true">
            <el-option v-for="item in options"
                       :key="item.operatorId"
                       :label="item.operatorName"
                       :value="item.operatorId" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务类型"
                      prop="serviceType"
                      class="aaa">
          <el-select v-model="ruleForm.serviceType"
                     placeholder="请选择"
                     @change="edited = true">
            <el-option label="船端"
                       value="SHIP_CLIENT" />
            <el-option label="岸端"
                       value="COAST_CLIENT" />
            <el-option label="船端+岸端"
                       value="SHIP_COAST_CLIENT" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="入驻船舶数"
                      prop="enteringShipNumber">
          <el-input v-model="ruleForm.enteringShipNumber"
                    size="small"
                    class="page-form-input"
                    @change="edited = true" />
        </el-form-item> -->
        <!-- 船舶总数量 -->
        <el-form-item label="入驻船舶数"
                      prop="shipNumber">
          <el-input v-model="ruleForm.shipNumber"
                    size="small"
                    class="page-form-input"
                    @change="edited = true" />
        </el-form-item>
        <el-form-item label="税务登记号"
                      prop="compImo">
          <el-input v-model="ruleForm.compImo"
                    @change="edited = true"
                    size="small"
                    class="page-form-input" />
        </el-form-item>
        <el-form-item label="合同时间"
                      prop="contractStartDate">
          <el-date-picker v-model="ruleForm.contractStartDate"
                          format="yyyy 年 MM 月 dd 日"
                          value-format="yyyy-MM-dd"
                          type="date"
                          placeholder="选择日期"
                          @change="edited = true" />
        </el-form-item>
        <el-form-item label="到期时间"
                      prop="contractEndDate">
          <el-date-picker v-model="ruleForm.contractEndDate"
                          format="yyyy 年 MM 月 dd 日"
                          value-format="yyyy-MM-dd"
                          type="date"
                          placeholder="选择日期"
                          @change="edited = true" />
        </el-form-item>
      </el-form>
    </div>
    <div class="head head2">
      <span class="headicon">开通服务</span>
    </div>
    <div class="top-buttons">
      <el-button size="small"
                 type="primary"
                 @click="addServe"
                 :loading="loading">开通服务</el-button>
    </div>
    <el-dialog title="开通服务"
               :visible.sync="dialogVisible"
               width="40%"
               :close-on-click-modal="false"
               @closed="handleDialogClosed">
      <el-collapse v-if="dialogVisible"
                   v-loading="loading">
        <el-collapse-item v-for="plugin in dialogTreeData"
                          :key="plugin.pluginCode">
          <template slot="title">
            <svg-icon icon-class="ship"
                      class="svg-icon" />
            <div class="plugin-name">{{ plugin.pluginName }}</div>
          </template>
          <div class="collapse-item-content">
            <div class="collapse-item-content-item">
              <div class="title">属性设置</div>
              <template v-for="(radioAttr, idx) in Object.values(plugin.radioAttribute)">
                <el-radio-group v-model="radioAttr.selected"
                                :key="idx">
                  <el-radio v-for="radio in radioAttr.options"
                            :key="radio.attributeCode"
                            :label="radio.attributeCode">{{ radio.attributeName }}</el-radio>
                </el-radio-group>
              </template>
              <el-checkbox v-for="attr in plugin.checkboxAttributes"
                           v-model="attr.selected"
                           :key="attr.attributeCode">
                {{ attr.attributeName }}
              </el-checkbox>
            </div>
            <div class="collapse-item-content-item">
              <div class="title">服务设置</div>
              <el-tree :data="plugin.pluginServers"
                       show-checkbox
                       :default-checked-keys="dialogDefaultCheckedKeyObj[plugin.pluginCode]"
                       @check-change="checkChange(plugin.pluginCode,'pluginService' + plugin.pluginCode)"
                       node-key="serviceCode"
                       :props="{ label: 'serviceName', children: 'children' }"
                       :ref="'pluginService' + plugin.pluginCode" />
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="handleDialogCancel"
                   :disabled="loading">取 消</el-button>
        <el-button type="primary"
                   @click="handleActive"
                   :loading="loading">确 定</el-button>
      </div>
    </el-dialog>
    <div class="activatedServices">
      <el-collapse>
        <el-collapse-item v-for="plugin in pageTreeData"
                          :key="plugin.pluginId">
          <div slot="title"
               class="payedPlugin">
            <div class="basic">
              <svg-icon icon-class="ship"
                        class="svg-icon" />
              <div class="plugin-name">{{ plugin.pluginName }}</div>
            </div>
            <div class="plugin-extra">
              <div>开通时间：{{ plugin.pluginOpenedDate }}</div>
              <div class="plugin-extra-end-date">到期时间：{{ plugin.pluginExpiredDate }}</div>
              <div class="plugin-extra-seperator"></div>
              <div class="plugin-extra-left-days"
                   :class="leftDays(plugin.pluginOpenedDate, plugin.pluginExpiredDate) < 100 && leftDays(plugin.pluginOpenedDate, plugin.pluginExpiredDate) >= 0 && 'red'">剩余天数：{{ { start: plugin.pluginOpenedDate, end: plugin.pluginExpiredDate } | leftDays }}天</div>
            </div>
          </div>
          <div class="collapse-item-content">
            <el-tree :data="plugin.activatedServices"
                     :props="{ label: 'label', children: 'tenantServiceItems' }"></el-tree>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script>
import {
  tenantChangeInfo,
  operators,
  tenantDetail,
  plugins,
  activablePlugins,
  activate,
  tenantChangeshipNumber,
  tenantcompIpm
} from "../../api/lessee";
import { validPhone, validEmail, isNumber } from "../../utils/validate";

const shipNumber = (rule, value, callback) => {
  if (value == null || value === "") {
    callback(new Error("带星号的不能为空"));
  } else if (!isNumber(value)) {
    callback(new Error("只能是正整数"));
  } else {
    callback();
  }
};
const checkEmail = (rule, value, callback) => {
  if (value == null || value === "") {
    callback();
  } else if (!validEmail(value)) {
    callback(new Error("邮箱格式不正确"));
  } else {
    callback();
  }
};
const validcodePhonee = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("带星号的不能为空"));
  } else if (!validPhone(value)) {
    callback(new Error("手机号格式填写错误"));
  } else {
    callback();
  }
};
export default {
  name: "Lessee",
  filters: {
    leftDays ({ start, end }) {
      return Math.floor(
        (new Date(end).getTime() - new Date(start).getTime()) /
        (1000 * 3600 * 24)
      );
    }
  },
  data () {
    return {
      state: true,
      rowMsg: "",
      showlist: "",
      tenantId: "",
      ruleForm: {
        
      },
      edited: false,
      rules: {
        tenantName: [
          {
            required: true,
            message: "",
            trigger: "blur"
          }
        ],
        tenantEnName: [
          {
            required: true,
            trigger: "blur"
          }
        ],
        compImo: [
          {
            required: true,
            trigger: "blur"
          }
        ],
        compSimpleNameEn: [
          {
            required: true,
            message: "",
            trigger: "blur"
          }
        ],
        compDomainName: [
          {
            required: true,
            message: "",
            trigger: "blur"
          }
        ],
        linkmanName: [
          {
            required: true,
            message: "",
            trigger: "blur"
          }
        ],
        serviceType: [
          {
            required: true,
            message: "",
            trigger: "blur"
          }
        ],
        linkmanPhone: [
          {
            required: true,
            validator: validcodePhonee,
            trigger: "blur"
          }
        ],
        customerServiceStaffId: [
          {
            required: true,
            message: "",
            trigger: "blur"
          }
        ],
        enteringShipNumber: [
          {
            required: true,
            message: "",
            trigger: "blur"
          }
        ],
        shipNumber: [
          {
            required: true,
            validator: shipNumber,
            message: "",
            trigger: "blur"
          }
        ],
        contractStartDate: [
          {
            required: true,
            validator: this.checkContractStartDate,
            trigger: "change"
          }
        ],
        contractEndDate: [
          {
            required: true,
            validator: this.checkContractEndDate,
            trigger: "change"
          }
        ],
        linkmanEmail: [
          {
            validator: checkEmail,
            trigger: "blur"
          }
        ]
      },
      options: [],
      dialogTreeData: [],
      dialogDefaultCheckedKeyObj: {},
      pageTreeData: [],
      loading: false,
      dialogVisible: false
    };
  },
  created () {
    if (this.$route.params.state === false) {
      this.state = false;
    } else {
      this.state = true;
    }
    this.tenantId = localStorage.getItem("tenantId");
    // 查询租户详细信息以及专属客服列表
    this.checkMsg();
    this.checkList();
    this.getPayedServices();
  },
  methods: {
    checkChange (key, ref) {
      const nodes = this.$refs[ref][0].getCheckedNodes(true, false);
      const keys = [];
      nodes.forEach(v => {
        keys.push(v.id);
      });
      this.$set(this.dialogDefaultCheckedKeyObj, key, keys);
    },
    leftDays (start, end) {
      return Math.floor(
        (new Date(end).getTime() - new Date(start).getTime()) /
        (1000 * 3600 * 24)
      );
    },
    checkList () {
      operators({
        currentPage: "",
        pageSize: ""
      }).then(response => {
        this.options = response.data.records;
      });
    },
    checkMsg () {
      tenantDetail({
        tenantId: this.tenantId
      }).then(response => {
        this.ruleForm = response.data;
        tenantcompIpm({
        compId: this.ruleForm.compId
      }).then(response1 => {
        this.$set(this.ruleForm,'compImo',response1.data.compImo)
      })
      });
    },
    // 合同时间验证
    checkContractStartDate (rule, value, callback) {
      this.$refs.ruleForm.clearValidate("contractEndDate");
      const end = this.ruleForm.contractEndDate;
      if (!value) {
        callback(new Error("合同开始日期不能为空"));
      } else if (end > value) {
        callback();
      } else {
        callback(new Error("合同开始日期须早于结束日期"));
      }
    },
    checkContractEndDate (rule, value, callback) {
      this.$refs.ruleForm.clearValidate("contractStartDate");
      const start = this.ruleForm.contractStartDate;
      if (!value) {
        callback(new Error("合同结束日期不能为空"));
      } else if (value > start) {
        callback();
      } else {
        callback(new Error("合同结束日期须晚于开始日期"));
      }
    },
    save () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          tenantChangeInfo(this.ruleForm)
            .then(response => {
              if (response.code === "MANAGEMENT_010") {
                this.$message({
                  message: "公司域名重复",
                  type: "error",
                  showClose: true
                });
              } else if (response.code === "OPERATION_001") {
                this.$message({
                  message: "用户名已存在",
                  type: "error",
                  showClose: true
                });
              } else if (response.code === "OPERATION_002") {
                this.$message({
                  message: "用户名已存在",
                  type: "error",
                  showClose: true
                });
              } else if (response.code === "OPERATION_003") {
                this.$message({
                  message: "公司中文名称/公司英文名称/手机号已被占用",
                  type: "error",
                  showClose: true
                });
              } else {
                
                tenantChangeshipNumber({compId:this.ruleForm.compId,compImo:this.ruleForm.compImo})
            .then(response => {
              this.$message({
                  message: "保存成功",
                  type: "success",
                  showClose: true
                });
            })
                this.$router.push({
                  name: "lessee"
                });
              }
            })
            .catch(() => {
              this.showlist = false;
              this.$message({
                message: "保存失败",
                type: "error",
                showClose: true
              });
            });
        } else {
          this.showlist = false;
          this.$message({
            message: "带星号的为必填项或格式填写错误",
            type: "error",
            showClose: true
          });
          return false;
        }
      });
    },
    back () {
      if (this.edited) {
        this.$confirm("租户信息尚未保存，确定要离开吗？", "提示", {
          type: "warning"
        })
          .then(() => {
            this.$router.push({
              name: "lessee"
            });
          })
          .catch(() => { });
      } else {
        this.$router.push({
          name: "lessee"
        });
      }
    },
    backToAdd () {
      this.$router.back();
    },
    async addServe () {
      await this.getAvailabelServices();
      this.dialogVisible = true;
    },
    handleDialogCancel () {
      this.dialogVisible = false;
    },
    handleDialogClosed () {
      this.dialogTreeData = [];
    },
    // 获取未选择的、可用的插件列表
    async getAvailabelServices () {
      this.loading = true;
      const response = await activablePlugins({ tenantId: this.tenantId });
      this.dialogTreeData = this.convertDialogTreeData(response.data);
      await this.getPayedServices();
      this.loading = false;
    },
    // 获取租户已购买的插件列表
    async getPayedServices (compare = true) {
      // debugger
      const response = await plugins({ tenantId: this.tenantId });
      console.log(response)
      this.pageTreeData = response.data.map(plugin => {
        if(plugin.activatedServices){
          return {
          ...plugin,
          activatedServices: plugin.activatedServices.map(service => {
            return {
              ...service,
              label: service.serviceName,
              tenantServiceItems: service.tenantServiceItems.map(item => {
                return { ...item, label: item.serviceItemName };
              })
            };
          })
        };
        }else{
          return {
          ...plugin,
          }
        }
        
      });
      // 如果dialog里有值，就对比勾选服务
      if (compare && this.dialogTreeData.length > 0) {
        this.pageTreeData.forEach(plugin => {
          let serviceCodes = [];
          if(plugin.activatedServices){
            plugin.activatedServices.forEach(service => {
            if (
              !service.tenantServiceItems ||
              service.tenantServiceItems.length === 0
            ) {
              serviceCodes.push(service.serviceCode);
            } else {
              serviceCodes = serviceCodes.concat(
                service.tenantServiceItems.map(itm => itm.serviceItemCode)
              );
            }
          });
          }
          
          this.dialogDefaultCheckedKeyObj[plugin.pluginCode] = serviceCodes;
        });
      }
    },
    // 开通服务
    handleActive () {
      const selectedServices = [];
      let pluginAttributes = [];
      for (let index = 0; index < this.dialogTreeData.length; index++) {
        const plugin = this.dialogTreeData[index];
        // 填写activatedServices字段
        const tree = this.$refs["pluginService" + plugin.pluginCode][0];
        const treeSelectedServices = tree.getCheckedNodes();
        const halfSelectedServices = tree.getHalfCheckedNodes();
        const tmp = treeSelectedServices.concat(halfSelectedServices);
        treeSelectedServices.forEach(itm => {
          if (itm.parentServiceCode !== "-1") {
            // 这个是serviceitem
            if (
              !selectedServices.some(
                item => item.serviceCode === itm.parentServiceCode
              )
            ) {
              // 没重复的service，则添加这个service
              const service = tmp.find(
                item => item.serviceCode === itm.parentServiceCode
              );
              const wantToAddService = {};
              wantToAddService.serviceCode = service.serviceCode;
              wantToAddService.pluginCode = service.pluginCode;
              wantToAddService.serviceExpiredDate =
                this.ruleForm.contractEndDate + " 00:00:00";
              wantToAddService.tenantServiceItems = [
                {
                  serviceItemCode: itm.serviceCode,
                  serviceItemName: itm.serviceName
                }
              ];
              selectedServices.push(wantToAddService);
            } else {
              // 有重复的，则直接往service的tenantServiceItems字段塞
              const service = selectedServices.find(
                item => item.serviceCode === itm.parentServiceCode
              );
              service.tenantServiceItems.push({
                serviceItemCode: itm.serviceCode,
                serviceItemName: itm.serviceName
              });
            }
          } else if (
            !itm.tenantServiceItems ||
            itm.tenantServiceItems.length === 0
          ) {
            // 只有service级，没有serviceItem级，则这个service也要加上
            selectedServices.push({
              serviceCode: itm.serviceCode,
              pluginCode: itm.pluginCode,
              serviceExpiredDate: this.ruleForm.contractEndDate + " 00:00:00",
              tenantServiceItems: []
            });
          }
        });
        // 填写pluginAttributes字段
        const radio = plugin.radioAttribute;
        for (let index = 0; index < Object.values(radio).length; index++) {
          const radioItem = Object.values(radio)[index];
          if (radioItem.selected) {
            pluginAttributes.push({ attributeCode: radioItem.selected, pluginCode: radioItem.pluginCode });
            // Todo：校验错误需要修改，应该先判断有无服务属性，然后再做检查，而且有的是radio有的是checkbox
            // } else {
            //   this.$message({
            //     message: '请先设置服务属性',
            //     type: 'error',
            //     showClose: true
            //   })
            //   return;
          }
        }
        const checkboxAttributeCode = plugin.checkboxAttributes
          .filter(itm => itm.selected)
          .map(item => {
            return { attributeCode: item.attributeCode, pluginCode: item.pluginCode };
          });
        pluginAttributes = pluginAttributes.concat(checkboxAttributeCode);
      }
      this.loading = true;
      activate({
        tenantId: this.tenantId,
        activatedServices: selectedServices,
        pluginAttributes
      })
        .then(() => {
          this.loading = false;
          this.$message({
            type: "success",
            message: "开通成功",
            showClose: true
          });
          this.dialogVisible = false;
          this.getPayedServices(false);
        })
        .catch(() => {
          this.loading = false;
          this.$message({
            type: "error",
            message: "开通失败",
            showClose: true
          });
        });
    },
    // Helper
    convertDialogTreeData (arr) {
      return arr.map(item => {
        const radioAttribute = {};
        const checkboxAttributes = [];
        item.pluginAttributes.forEach(attr => {
          if (attr.multipleChoiceFlag === "1") {
            if (radioAttribute[attr.attributeType]) {
              radioAttribute[attr.attributeType].options.push(attr);
            } else {
              radioAttribute[attr.attributeType] = {
                selected: "",
                options: [attr]
              };
            }
            if (!radioAttribute[attr.attributeType].selected) {
              radioAttribute[attr.attributeType].selected = attr.isOpening
                ? attr.attributeCode
                : "";
            }
            radioAttribute[attr.attributeType].pluginCode = item.pluginCode
          } else {
            attr.selected = attr.isOpening;
            checkboxAttributes.push(attr);
          }
        });
        let newVar = {
          ...item,
          radioAttribute,
          checkboxAttributes,
          pluginServers: item.pluginServers.map(service => {
            return { ...service, pluginCode: item.pluginCode };
          })
        };
        return newVar;
      });
    }
  }
};
</script>

<style scoped lang="scss">
@import "../../styles/variables.scss";
.form,
.head2 {
  margin-top: 40px;
}
.talk {
  color: #666666;
  cursor: pointer;
  height: 19px;
  line-height: 19px;
  font-size: 25px;
}
.activatedServices {
  margin-top: 20px;
}
.first-level-tree-node {
  .property {
    display: flex;
  }
}
.collapse-item-content {
  padding-left: 32px;
}
.collapse-item-content-item {
  line-height: 2;
  // display: flex;
  .title {
    margin-right: 8px;
  }
}
.svg-icon,
.plugin-name {
  margin-left: 8px;
}
.payedPlugin {
  width: 100%;
  display: flex;
  justify-content: space-between;
  .basic {
    display: flex;
    align-items: center;
  }
}
.plugin-extra {
  display: flex;
  align-items: center;
  .plugin-extra-end-date {
    margin-left: 16px;
  }
  .plugin-extra-seperator {
    margin-left: 8px;
    height: 14px;
    background-color: #999;
    width: 1px;
  }
  .plugin-extra-left-days {
    margin-left: 8px;
  }
  .red {
    color: $red;
  }
}
.aaa {
  /deep/.el-form-item__error {
    display: none;
  }
}
</style>
