import "choerodon-ui/pro/lib/data-set/style";
import _DataSet from "choerodon-ui/pro/lib/data-set";

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

import BaseComDeployApis from "../apis";
import BaseComDeployServices from "../services";
import uuidV1 from 'uuid/v1';
import { axios } from '@choerodon/master'; // eslint-disable-next-line import/no-cycle

import { mapping as paramsMapping } from "./paramSettingDataSet";
var deployWayOptionsData = [{
  text: '容器部署',
  value: 'env'
}, {
  text: '主机部署',
  value: 'host'
}];
var deployModeOptionsData = [{
  text: '单机模式',
  value: 'standalone'
}, {
  text: '哨兵模式',
  value: 'sentinel'
}];
var mySqlDeployModeOptionsData = [{
  text: '单机模式',
  value: 'standalone'
}, {
  text: '主备模式',
  value: 'master-slave'
}];

function checkResourceName(_x, _x2, _x3, _x4) {
  return _checkResourceName.apply(this, arguments);
}

function _checkResourceName() {
  _checkResourceName = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(value, name, record, projectId) {
    var pa;
    return regeneratorRuntime.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            pa = /^[a-z]([-a-z0-9]*[a-z0-9])?$/;

            if (!(value && pa.test(value))) {
              _context2.next = 3;
              break;
            }

            return _context2.abrupt("return", true);

          case 3:
            return _context2.abrupt("return", '名称只能由小写字母、数字、"-"组成，且以小写字母开头，不能以"-"结尾');

          case 4:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  }));
  return _checkResourceName.apply(this, arguments);
}

function checkName(_x5, _x6, _x7, _x8) {
  return _checkName.apply(this, arguments);
}

function _checkName() {
  _checkName = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(value, name, record, projectId) {
    var pa, res;
    return regeneratorRuntime.wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            pa = /^[a-z]([-a-z0-9]*[a-z0-9])?$/;

            if (!(value && pa.test(value))) {
              _context3.next = 18;
              break;
            }

            if (record.get(mapping.env.name)) {
              _context3.next = 4;
              break;
            }

            return _context3.abrupt("return");

          case 4:
            _context3.prev = 4;
            _context3.next = 7;
            return axios.get("/devops/v1/projects/".concat(projectId, "/app_service_instances/check_name?instance_name=").concat(value, "&env_id=").concat(record.get(mapping.env.name)));

          case 7:
            res = _context3.sent;

            if (!(res && res.failed || !res)) {
              _context3.next = 10;
              break;
            }

            return _context3.abrupt("return", '名称已存在');

          case 10:
            return _context3.abrupt("return", true);

          case 13:
            _context3.prev = 13;
            _context3.t0 = _context3["catch"](4);
            return _context3.abrupt("return", '名称重名校验失败，请稍后再试');

          case 16:
            _context3.next = 19;
            break;

          case 18:
            return _context3.abrupt("return", '名称只能由小写字母、数字、"-"组成，且以小写字母开头，不能以"-"结尾');

          case 19:
            return _context3.abrupt("return", true);

          case 20:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, null, [[4, 13]]);
  }));
  return _checkName.apply(this, arguments);
}

var middleWareData = [{
  value: 'Redis',
  text: 'redis'
}, {
  value: 'MySQL',
  text: 'mysql'
}];
var mapping = {
  password: {
    name: 'password',
    type: 'string',
    label: '密码',
    defaultValue: 'Changeit!123'
  },
  sysctlImage: {
    name: 'sysctlImage',
    type: 'boolean',
    label: 'sysctlImage',
    defaultValue: false
  },
  virtualIp: {
    name: 'virtualIp',
    type: 'string',
    label: '虚拟IP'
  },
  slaveCount: {
    name: 'slaveCount',
    type: 'number',
    min: 3,
    step: 1,
    label: 'slaveCount',
    defaultValue: 3
  },
  middleware: {
    name: 'middleware',
    defaultValue: middleWareData[0].value,
    type: 'string',
    options: new _DataSet({
      data: middleWareData
    })
  },
  serviceVersion: {
    name: 'version',
    type: 'string',
    label: '服务版本',
    required: true,
    textField: 'versionNumber',
    valueField: 'versionNumber'
  },
  deployWay: {
    name: 'deployWay',
    type: 'string',
    label: '部署方式',
    textField: 'text',
    valueField: 'value',
    defaultValue: deployWayOptionsData[0].value,
    options: new _DataSet({
      data: deployWayOptionsData
    })
  },
  deployMode: {
    name: 'mode',
    type: 'string',
    label: '部署模式',
    textField: 'text',
    valueField: 'value',
    defaultValue: deployModeOptionsData[0].value,
    options: new _DataSet({
      data: deployModeOptionsData
    })
  },
  resourceName: {
    name: 'resourceName',
    type: 'string',
    label: '资源名称',
    maxLength: 64
  },
  env: {
    name: 'environmentId',
    type: 'string',
    label: '环境',
    textField: 'name',
    valueField: 'id'
  },
  instance: {
    name: 'instanceName',
    type: 'string',
    label: '实例名称',
    // defaultValue: `${middleWareData[0].value}-${uuidV1().substring(0, 5)}`,
    maxLength: 64
  },
  pvc: {
    textField: 'name',
    valueField: 'name',
    name: 'pvcName',
    type: 'string',
    label: 'PVC'
  },
  values: {
    name: 'values',
    type: 'string',
    defaultValue: ''
  }
};
export { mapping, deployWayOptionsData, deployModeOptionsData, middleWareData, mySqlDeployModeOptionsData };
export default (function (projectId, HostSettingDataSet, BaseComDeployStore, ServiceVersionDataSet) {
  return {
    autoCreate: true,
    fields: Object.keys(mapping).map(function (key) {
      var item = mapping[key];

      if (key === 'serviceVersion') {
        item.options = ServiceVersionDataSet; // item.lookupAxiosConfig = () => ({
        //   url: BaseComDeployApis
        //     .getServiceVersionApi(middleWareData[0].value),
        //   method: 'get',
        //   transformResponse: (res) => {
        //     debugger;
        //     function finalFunc(data) {
        //       debugger;
        //       if (data.length && data.length > 0) {
        //         BaseComDeployStore.setServiceVersionList(data);
        //         // if (record) {
        //         //   record.set(mapping.serviceVersion.name, data[0].versionNumber);
        //         // }
        //       }
        //     }
        //     let newRes = res;
        //     try {
        //       debugger;
        //       newRes = JSON.parse(newRes);
        //       finalFunc(newRes);
        //       return newRes;
        //     } catch (e) {
        //       debugger;
        //       finalFunc(newRes);
        //       return newRes;
        //     }
        //   },
        // });
      } else if (key === 'password') {
        item.dynamicProps = {
          required: function required(_ref) {
            var record = _ref.record;
            return record.get(mapping.deployWay.name) === deployWayOptionsData[0].value;
          }
        };
      } else if (key === 'sysctlImage') {
        item.dynamicProps = {
          required: function required(_ref2) {
            var record = _ref2.record;
            return record.get(mapping.middleware.name) === middleWareData[0].value && record.get(mapping.deployWay.name) === deployWayOptionsData[0].value;
          }
        };
      } else if (key === 'slaveCount') {
        item.dynamicProps = {
          required: function required(_ref3) {
            var record = _ref3.record;
            return record.get(mapping.middleware.name) === middleWareData[0].value && record.get(mapping.deployWay.name) === deployWayOptionsData[0].value && record.get(mapping.deployMode.name) === deployModeOptionsData[1].value;
          }
        };
      } else if (key === 'pvc') {
        item.dynamicProps = {
          lookupAxiosConfig: function lookupAxiosConfig(_ref4) {
            var record = _ref4.record;
            return record.get(mapping.env.name) ? {
              url: BaseComDeployApis.getPvcListApi(projectId, record.get(mapping.env.name)),
              method: 'post',
              data: {
                params: [],
                searchParam: {
                  status: 'Bound',
                  used: 0
                }
              }
            } : undefined;
          }
        };
      } else if (key === 'env') {
        item.lookupAxiosConfig = function () {
          return {
            url: BaseComDeployApis.getEnvListApi(projectId),
            method: 'get',
            transformResponse: function transformResponse(res) {
              var newRes = res;

              try {
                newRes = JSON.parse(newRes);
                BaseComDeployStore.setEnvList(newRes);
                return newRes;
              } catch (e) {
                BaseComDeployStore.setEnvList(newRes);
                return newRes;
              }
            }
          };
        };

        item.dynamicProps = {
          required: function required(_ref5) {
            var record = _ref5.record;
            return record.get(mapping.deployWay.name) === deployWayOptionsData[0].value;
          }
        };
      } else if (key === 'instance') {
        item.validator = function (value, name, record) {
          return checkName(value, name, record, projectId);
        };

        item.dynamicProps = {
          required: function required(_ref6) {
            var record = _ref6.record;
            return record.get(mapping.deployWay.name) === deployWayOptionsData[0].value;
          }
        };
        item.defaultValue = "".concat(middleWareData[0].text, "-").concat(uuidV1().substring(0, 5));
      } else if (key === 'resourceName') {
        item.dynamicProps = {
          required: function required(_ref7) {
            var record = _ref7.record;
            return record.get(mapping.deployWay.name) === deployWayOptionsData[1].value;
          }
        };

        item.validator = function (value, name, record) {
          if (record.get(mapping.deployWay.name) === deployWayOptionsData[1].value) {
            return checkResourceName(value, name, record, projectId);
          }

          return true;
        };

        item.defaultValue = "".concat(middleWareData[0].text, "-").concat(uuidV1().substring(0, 5));
      } else if (key === 'virtualIp') {
        item.dynamicProps = {
          required: function required(_ref8) {
            var record = _ref8.record;
            return record.get(mapping.middleware.name) === middleWareData[1].value && record.get(mapping.deployWay.name) === deployWayOptionsData[1].value && record.get(mapping.deployMode.name) === mySqlDeployModeOptionsData[1].value;
          }
        };

        item.validator = function (value, name, record) {
          function isValidIP(ip) {
            var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
            return reg.test(ip);
          }

          var flag = record.get(mapping.middleware.name) === middleWareData[1].value && record.get(mapping.deployWay.name) === deployWayOptionsData[1].value && record.get(mapping.deployMode.name) === mySqlDeployModeOptionsData[1].value;

          if (!flag) {
            return true;
          }

          var result = isValidIP(value);

          if (result) {
            return result;
          }

          return '请输入正确格式的ip地址';
        };
      }

      return item;
    }),
    events: {
      update: function () {
        var _update = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref9) {
          var dataSet, record, name, value;
          return regeneratorRuntime.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  dataSet = _ref9.dataSet, record = _ref9.record, name = _ref9.name, value = _ref9.value;
                  _context.t0 = name;
                  _context.next = _context.t0 === mapping.deployWay.name ? 4 : _context.t0 === mapping.middleware.name ? 6 : _context.t0 === mapping.deployMode.name ? 10 : _context.t0 === mapping.serviceVersion.name ? 12 : 13;
                  break;

                case 4:
                  // 主机部署
                  if (value === deployWayOptionsData[1].value) {
                    // mysql
                    if (record.get(mapping.middleware.name) === middleWareData[1].value) {
                      record.set(mapping.deployMode.name, mySqlDeployModeOptionsData[1].value);
                    } // 单机


                    if (record.get(mapping.deployMode.name) === deployModeOptionsData[0].value) {
                      HostSettingDataSet.splice(0, HostSettingDataSet.records.length);

                      if (record.get(mapping.middleware.name) === middleWareData[1].value) {
                        //  mysql
                        HostSettingDataSet.create({
                          checked: true
                        });
                        HostSettingDataSet.records.forEach(function (i) {
                          i.setState('params', new _DataSet({
                            paging: false,
                            selection: false,
                            data: BaseComDeployStore.getMysqlParams,
                            fields: Object.keys(paramsMapping).map(function (key) {
                              return paramsMapping[key];
                            })
                          }));
                        });
                      } else {
                        // redis
                        HostSettingDataSet.create();
                      }
                    } else {
                      HostSettingDataSet.splice(0, HostSettingDataSet.records.length);

                      if (record.get(mapping.middleware.name) === middleWareData[1].value) {
                        HostSettingDataSet.create({
                          checked: true
                        });
                        HostSettingDataSet.create({
                          checked: false
                        });
                        HostSettingDataSet.records.forEach(function (i) {
                          i.setState('params', new _DataSet({
                            paging: false,
                            selection: false,
                            data: BaseComDeployStore.getMysqlParams,
                            fields: Object.keys(paramsMapping).map(function (key) {
                              return paramsMapping[key];
                            })
                          }));
                        });
                      } else {
                        HostSettingDataSet.create();
                        HostSettingDataSet.create();
                        HostSettingDataSet.create();
                      }
                    }
                  }

                  return _context.abrupt("break", 14);

                case 6:
                  record.set(mapping.instance.name, "".concat(middleWareData.find(function (i) {
                    return i.value === value;
                  }).text, "-").concat(uuidV1().substring(0, 5)));
                  record.set(mapping.resourceName.name, "".concat(middleWareData.find(function (i) {
                    return i.value === value;
                  }).text, "-").concat(uuidV1().substring(0, 5))); // 如果是mysql

                  if (value === middleWareData[1].value) {
                    record.getField(mapping.deployMode.name).options.loadData(mySqlDeployModeOptionsData);
                    record.set(mapping.deployMode.name, mySqlDeployModeOptionsData[1].value); // 如果部署方式是容器部署

                    if (record.get(mapping.deployWay.name) === deployWayOptionsData[0].value) {
                      record.set(mapping.deployMode.name, mySqlDeployModeOptionsData[0].value);
                    }
                  } else {
                    record.getField(mapping.deployMode.name).options.loadData(deployModeOptionsData);
                    record.set(mapping.deployMode.name, deployModeOptionsData[1].value);
                  } // 重查serviceVersion options
                  // result = await BaseComDeployServices.axiosGetServiceVersion(value);
                  // BaseComDeployStore.setServiceVersionList(result);
                  // console.log(dataSet.current.getField(mapping.serviceVersion.name));
                  // dataSet.current.getField(mapping.serviceVersion.name).options.splice(0, 1, result);


                  return _context.abrupt("break", 14);

                case 10:
                  // 如果是主机部署
                  if (record.get(mapping.deployWay.name) === deployWayOptionsData[1].value) {
                    if (value === deployModeOptionsData[0].value) {
                      HostSettingDataSet.splice(0, HostSettingDataSet.records.length);

                      if (record.get(mapping.middleware.name) === middleWareData[1].value) {
                        //  mysql
                        HostSettingDataSet.create({
                          checked: true
                        });
                        HostSettingDataSet.records.forEach(function (i) {
                          i.setState('params', new _DataSet({
                            paging: false,
                            selection: false,
                            data: BaseComDeployStore.getMysqlParams,
                            fields: Object.keys(mapping).map(function (key) {
                              return mapping[key];
                            })
                          }));
                        });
                      } else {
                        // redis
                        HostSettingDataSet.create();
                      }
                    } else {
                      HostSettingDataSet.splice(0, HostSettingDataSet.records.length);

                      if (record.get(mapping.middleware.name) === middleWareData[1].value) {
                        HostSettingDataSet.create({
                          checked: true
                        });
                        HostSettingDataSet.create({
                          checked: false
                        });
                        HostSettingDataSet.records.forEach(function (i) {
                          i.setState('params', new _DataSet({
                            paging: false,
                            selection: false,
                            data: BaseComDeployStore.getMysqlParams,
                            fields: Object.keys(mapping).map(function (key) {
                              return mapping[key];
                            })
                          }));
                        });
                      } else {
                        HostSettingDataSet.create();
                        HostSettingDataSet.create();
                        HostSettingDataSet.create();
                      }
                    }
                  } else {//  如果是环境部署
                    // const deployMode = value;
                    // const serviceVersion = record.get(mapping.serviceVersion.name);
                    // const lookupData = BaseComDeployStore.getServiceVersionList;
                    // const appVersionId = lookupData
                    //   .find((item) => item.versionNumber === serviceVersion).id;
                    // const result = await BaseComDeployServices
                    //   .axiosGetMiddlewareValue(appVersionId, deployMode);
                    // record.set(mapping.values.name, result || '');
                  }

                  return _context.abrupt("break", 14);

                case 12:
                  return _context.abrupt("break", 14);

                case 13:
                  return _context.abrupt("break", 14);

                case 14:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee);
        }));

        function update(_x9) {
          return _update.apply(this, arguments);
        }

        return update;
      }()
    }
  };
});