<template>
  <page-layout :desc="desc">
    <div class="page-body">

      <vxe-form :data="formOptions.data" ref="xForm" :title-width="formOptions.titleWidth"
        :title-align="formOptions.titleAlign" :rules="formOptions.rules" :items="formOptions.items" titleColon>

        <template #company_type="{ data }">
          <a-select :default-value="companyTypeData[0]" v-model="data.company_type" style="width: 100%">
            <a-select-option v-for="companyType in companyTypeData" :key="companyType">
              {{ companyType }}
            </a-select-option>
          </a-select>
        </template>
        <template #beid="{ data }">
          <a-select v-model="data.beid" v-if="!isEdit" style="width: 100%">
            <a-select-option v-for=" item  in config_list" :key="item.id" :value="item.id">
              {{ item.title }}
            </a-select-option>
          </a-select>
          <div v-else>
            {{ currentConfigName || "无" }}
          </div> 
        </template>
        <template #logo="{}">
          <div class="imagePanel">
            <img :src="formOptions.data.logo || uploadDefaultImg" @click.stop="selectFile()">
          </div>
        </template>

      </vxe-form>

      <div class="mk-toolbar" v-if="isEdit">
        <a-button type="primary" @click="pageAdd">增加服务</a-button>
        <a-button @click="pageDel">删除服务</a-button>
      </div>
      <div class="gridPanel" v-if="isEdit">
        <vxe-grid ref='gridService' v-bind="gridServiceOptions">
          <template #status="{ row }">
            <a-switch :checked="row.status ? true : false" @change="onSwitch(row, 'status')" />
          </template>

        </vxe-grid>
      </div>


      <div class="footerbar">
        <a-button type="primary" @click="ok">确定</a-button>
        <a-button @click="cancel">取消</a-button>
      </div>

      <input type="file" ref="imageInput" @change="upload()" style="display:none;">
    </div>
  </page-layout>
</template>

<script>
import BASE_URL from '@/services/base/api.js';
import PageLayout from '@/layouts/PageLayout'

let serviceListPage = () => import("../BaseService/list");

export default {

  name: 'BaseCompanyUpdate',
  i18n: require('./i18n'),
  components: { PageLayout },
  props: {
    pageMode: {
      type: String,
      default: "edit"
    },
    dataId: {
    }

  },

  data() {

    // 页面数据变量
    var pageData = {

      companyTypeData: ['日用陶瓷厂', '卫浴工厂', '公司企业', '贸易公司', '其他'],
      config_list: [],
      currentConfigName: "",
      currentBeid: 0,

      uploadDefaultImg: null,

      actions: {
        create: `${BASE_URL.BASE_URL}/BaseCompany/v1/create`,
        update: `${BASE_URL.BASE_URL}/BaseCompany/v1/update`,
        get: `${BASE_URL.BASE_URL}/BaseCompany/v1/detail`,
        configList: `${BASE_URL.BASE_URL}/BaseConfig/v1/list`,
        serviceList: `${BASE_URL.BASE_URL}/BaseCompany/v1/service/list`,
        serviceAdd: `${BASE_URL.BASE_URL}/BaseCompany/v1/service/batchInsert`,
        serviceDel: `${BASE_URL.BASE_URL}/BaseCompany/v1/service/batchDelete`,
        serviceOpen: `${BASE_URL.BASE_URL}/BaseCompany/v1/service/open`,
        serviceClose: `${BASE_URL.BASE_URL}/BaseCompany/v1/service/close`
      },

      keyName: 'id',
      isEdit: false,
      formOptions: {
        data: {
          "beid": 0,
          "ptyid": 0,
          "title": "",
          "agentid": 0,
          "logo": "",
          "desc": "",
          "domain": "",
          "devdomain": "",
          "company_type": "日用陶瓷厂",
          "address": "",
          "longitude": "",
          "latitude": "",
          "appid": "",
          "appsecret": "",
          "is_private_cloud": 0,
          "auth_stop_date": new Date(2100, 1, 1).getTime() / 10000,
          "status": 1,
          "short_title": "",
          "token": "",
          "name": "",
          "mobile": "",
          "password": "",
          "email": "",
          "admin_count": 0,
          "staff_count": 0,
          "store_count": 0
        },

        titleWidth: 100,
        titleAlign: 'right',

        rules: {
          title: [
            { required: true, message: '请输入标题' }
          ],
          beid: [
            { required: true, message: '请选择归属项目' }
          ],
          company_type: [
            { required: true, message: '请选择公司类型' }
          ],
          name: [
            { required: true, message: '请输入管理员名称' }
          ],
          mobile: [
            { required: true, message: '请输入管理员手机号码' }
          ],
          password: [
            { required: true, message: '请输入管理员密码' }
          ],
          access_expire: [
            { required: true, message: '请输入登录过期截止时间' }
          ],
        },

        items: [
          { field: 'title', title: '公司名', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入公司名' } } },
          { field: 'short_title', title: '公司简称', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入公司简称' } } },
          { field: 'desc', title: '描述', span: 24, itemRender: { name: '$textarea', props: { placeholder: '请输入描述' } } },
          { field: 'logo', title: 'Logo', slots: { default: 'logo' }, span: 24 },
          { field: 'domain', title: '域名', span: 12, itemRender: { name: '$input' } },
          { field: 'devdomain', title: '测试域名', span: 12, itemRender: { name: '$input' } },
          { field: 'beid', title: '归属项目', span: 12, slots: { default: 'beid' } },
          { field: 'company_type', title: '公司类型', span: 12, slots: { default: 'company_type' } },
          { field: 'appid', title: 'AppID', span: 24, itemRender: { name: '$input' } },
          { field: 'appsecret', title: 'AppSecret', span: 24, itemRender: { name: '$input' } },
          { field: 'token', title: '企业Token', span: 24, itemRender: { name: '$textarea', props: { placeholder: '不用填写' } } },
          { field: 'access_expire', dataRule: { type: "timestamp" }, title: '登录过期截止时间', span: 24, itemRender: { name: '$input', props: {type:"date", placeholder: '输入登录过期截止时间' } } },


          
        ]
      },

      addModeItems: [

        { field: 'mobile', dataRule: { type: "integer" }, title: '管理员手机', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入管理员手机号' } } },
        { field: 'password', title: '管理员密码', span: 12, itemRender: { name: '$input', props: { type: "password", placeholder: '请输入管理员密码' } } },
        { field: 'name', title: '管理员名称', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入管理员名称' } } },
        { field: 'email', title: '管理员邮箱', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入管理员邮箱' } } }
      ],

      //服务管理 - 数据区
      gridServiceOptions: {
        height: '110%',
        id: 'datagrid_service_1',

        proxyConfig: {
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为 
          props: {
            result: 'service_detail', // 配置响应结果列表字段
            total: 'total' // 配置响应结果总页数字段
          },
          // 接收Promise
          ajax: {
            // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
            query: (options) => {
              const { page, sorts } = options;
              var params = {};
              params.page = page.currentPage;
              params.limit = page.pageSize;
              params.order_bys = [];
              params.search_rules = [];
              if (sorts) {
                sorts.forEach((v) => {
                  params.order_bys.push({
                    column: v.property,
                    order: v.order
                  })
                });
              }
              return this.loadDetailData1({ params });
            }
          }
        },
        columns: [
          { type: 'checkbox', width: 50 },
          { type: 'seq', width: 50 },
          { field: 'name', sortable: true, title: '服务名' },
          { field: 'title', sortable: true, title: '标题', showHeaderOverflow: true },
          { field: 'port', sortable: true, title: '端口', showHeaderOverflow: true },
          { field: 'status', sortable: true, title: '是否启用', slots: { default: 'status' } }
        ]
      }

    };
    pageData.gridServiceOptions = Object.assign({}, this.$mk.config.defaults.gridOptions, pageData.gridServiceOptions);
    pageData.formOptions = Object.assign({}, this.$mk.config.defaults.formOptions, pageData.formOptions);

    return pageData;
  },
  computed: {
    desc() {
      return this.$t('editPageDesc')
    }
  },
  created() {

    this.uploadDefaultImg = this.$mk.config.uploadDefaultImg;

    let dataId = this.getDataId();
    if (dataId) {



      this.$mk.post({
        url: this.actions.get,
        loading: "加载中...",
        data: {
          id: parseInt(dataId)
        }
      }).then(a => {
        if(a.data.BaseCompany.access_expire){
          a.data.BaseCompany.access_expire = new Date(a.data.BaseCompany.access_expire * 1000);
        }
        this.formOptions.data = a.data.BaseCompany;
        this.currentBeid = this.formOptions.data.beid;
        this.updateCurrentConfigName();
        console.log(this.currentBeid)
      }).catch((a) => {
        this.$mk.error(a.data.msg);
      });

      this.isEdit = true;
    } else {
      this.addModeItems.forEach(item => {
        this.formOptions.items.push(item);
      })

    }


    this.$mk.getPagedData({
      url: this.actions.configList, data: {
        "page": 0,
        "limit": 0,
        "start_time": 0,
        "end_time": 0,
        "search_rules": [
        ],
        "order_bys": [
        ]
      }
    }).then(r => {
      this.config_list = r.list;
      this.updateCurrentConfigName();

      this.config_list.splice(0, 0, { id: 0, title: "请选择" })
    });

  },
  // 函数
  methods: {

    updateCurrentConfigName() {
      this.config_list.forEach(item => {
        if (item.id == this.currentBeid) {
          this.currentConfigName = item.title;
        }

      })
    },

    selectFile() {
      this.$refs.imageInput.click();
    },
    upload() {
      const imgFile = this.$refs.imageInput.files[0]
      this.$mk.uploadFile(imgFile, 'png', (url) => {
        this.formOptions.data.logo = url;
      });
    },
    onSwitch(row) {
      row.status = row.status ? 0 : 1;
      this.$mk.post({
        url: row.status ? this.actions.serviceOpen : this.actions.serviceClose,
        data: { id: row.id },
      }).then(() => {
        this.$mk.msg(row.status ? "开启服务完成" : "停止服务完成");
        this.$emit("callback", { success: true });
      }).catch((a) => {
        this.$mk.error(a.data.msg);
      });

    },
    getDataId() {

      let dataId = this.dataId;
      if (this.$route.params.id) {
        dataId = this.$route.params.id;
      }
      return parseInt(dataId || 0);
    },
    loadDetailData1({ params }) {


      params.start_time = 0;
      params.end_time = 0;
      params.beid = this.formOptions.data.beid;
      params.ptyid = 0;
      params.company_id = this.getDataId();
      return this.$mk.getPagedData({ url: this.actions.serviceList, data: params });
    },
    back() {
      if (!this.isEdit) {
        this.$closePage({
          closeRoute: "/BaseCompany/BaseCompanyAdd"
        });
      } else {
        this.$closePage({
          closeRoute: "/BaseCompany/BaseCompanyUpdate"
        });
      }
      this.$openPage('/BaseCompany/BaseCompanyList')
    },
    ok() {

      let save = () => {
        let action = !this.isEdit ? this.actions.create : this.actions.update;
        let postdata = !this.isEdit ? Object.assign({ id: this.dataId }, this.formOptions.data) : Object.assign({}, this.formOptions.data);
        if (this.isEdit) {
          // postdata = { BaseCompany: postdata }
        }

        this.$mk.formatFormData({ data: postdata, rules: this.formOptions.items });

        this.$mk.post({
          url: action,
          loading: "保存中...",
          data: postdata,
        }).then(() => {
          this.$mk.success("保存成功");
          if (!this.isEdit) {
            this.back();
          }
        }).catch((a) => {
          this.$mk.error(a.data.msg);
        });
      };

      this.$mk.validateForm({ form: this.$refs.xForm }).then(() => {

        save();
      }).catch(count => {
        this.$mk.error(`存在${count}项错误，请检查`);
      });


    },
    pageDel() {
      let rows = this.$refs.gridService.getCheckboxRecords();
      let ids = [];
      rows.forEach((row) => {
        ids.push(row[this.keyName]);

      });

      if (!ids.length) {
        this.$mk.error("请选择行");
        return;
      }

      this.$mk.confirm('您确定要移除服务吗？').then(type => {
        if (type == 'confirm') {
          this.$mk.post({
            url: this.actions.serviceDel,
            loading: "移除服务中...",
            data: {
              ids: ids
            }
          }).then(() => {
            this.$mk.success("移除服务成功");
            this.$refs.gridService.commitProxy('query')
          }).catch((a) => {
            this.$mk.error(a.data.msg);
          });
        }
      });

    },
    pageAdd() {
      this.$mk.dialog.open({
        page: serviceListPage,
        title: "选择要添加的服务",

        showFooter: true,
        pageOptions: {
          config_id: this.currentBeid
        },
        pageMode: "select",
        width: 1000,
        height: 870,
        dataId: 0,
        callback: ({ data }) => {
          if (!data || !data.length) {
            return;
          }
          let ids = [];
          data.forEach(item => {
            ids.push(item.id)
          })
          this.$mk.post({
            url: this.actions.serviceAdd,
            loading: "添加中...",
            data: {
              "company_id": this.getDataId(),
              ptyid: 0,
              beid: this.formOptions.data.beid,
              "services_id": ids
            },
          }).then(() => {
            this.$mk.success("添加成功");

            this.$refs.gridService.commitProxy('query')
          }).catch((a) => {
            this.$mk.error(a.data.msg);
          });
        }
      });
    },
    cancel() {
      this.back();
    }
  },
  // 监听属性
  watch: {

  }
};

</script>
<style scoped lang="less">
.page-body {
  padding: 30px;
  background: @base-bg-color;
}

.formtabs .ant-tabs-tabpane {
  /* background: white; */
  padding: 12px;
}

.gridPanel {
  height: calc(100vh - 600px);
}

.footerbar {
  padding-left: 10px;
}

.imagePanel {
  cursor: pointer;
  padding: 10px;
  width: 100px;

  img {
    width: 80px;
    height: 80px;
  }
}
</style>
